llama.cpp 225 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372
  1. // Defines fileno on msys:
  2. #ifndef _GNU_SOURCE
  3. #define _GNU_SOURCE
  4. #endif
  5. #include "llama.h"
  6. #include "ggml.h"
  7. #include "ggml-alloc.h"
  8. #ifdef GGML_USE_CUBLAS
  9. # include "ggml-cuda.h"
  10. #elif defined(GGML_USE_CLBLAST)
  11. # include "ggml-opencl.h"
  12. #endif
  13. #ifdef GGML_USE_METAL
  14. # include "ggml-metal.h"
  15. #endif
  16. #ifdef GGML_USE_MPI
  17. # include "ggml-mpi.h"
  18. #endif
  19. #ifdef GGML_USE_K_QUANTS
  20. # ifndef QK_K
  21. # ifdef GGML_QKK_64
  22. # define QK_K 64
  23. # else
  24. # define QK_K 256
  25. # endif
  26. # endif
  27. #endif
  28. #ifdef __has_include
  29. #if __has_include(<unistd.h>)
  30. #include <unistd.h>
  31. #if defined(_POSIX_MAPPED_FILES)
  32. #include <sys/mman.h>
  33. #endif
  34. #if defined(_POSIX_MEMLOCK_RANGE)
  35. #include <sys/resource.h>
  36. #endif
  37. #endif
  38. #endif
  39. #if defined(_WIN32)
  40. #define WIN32_LEAN_AND_MEAN
  41. #ifndef NOMINMAX
  42. #define NOMINMAX
  43. #endif
  44. #include <windows.h>
  45. #include <io.h>
  46. #include <stdio.h> // for _fseeki64
  47. #endif
  48. #include <algorithm>
  49. #include <array>
  50. #include <cassert>
  51. #include <cinttypes>
  52. #include <climits>
  53. #include <cstdarg>
  54. #include <cstddef>
  55. #include <cstdint>
  56. #include <cstdio>
  57. #include <cstring>
  58. #include <ctime>
  59. #include <fstream>
  60. #include <initializer_list>
  61. #include <map>
  62. #include <memory>
  63. #include <mutex>
  64. #include <numeric>
  65. #include <queue>
  66. #include <random>
  67. #include <regex>
  68. #include <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. //
  84. // logging
  85. //
  86. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  87. static void llama_log_internal (llama_log_level level, const char* format, ...);
  88. static void llama_log_callback_default(llama_log_level level, const char * text, void * user_data);
  89. #define LLAMA_LOG_INFO(...) llama_log_internal(LLAMA_LOG_LEVEL_INFO , __VA_ARGS__)
  90. #define LLAMA_LOG_WARN(...) llama_log_internal(LLAMA_LOG_LEVEL_WARN , __VA_ARGS__)
  91. #define LLAMA_LOG_ERROR(...) llama_log_internal(LLAMA_LOG_LEVEL_ERROR, __VA_ARGS__)
  92. //
  93. // helpers
  94. //
  95. static size_t utf8_len(char src) {
  96. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  97. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  98. return lookup[highbits];
  99. }
  100. void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  101. std::string result;
  102. for (size_t pos = 0; ; pos += search.length()) {
  103. auto new_pos = s.find(search, pos);
  104. if (new_pos == std::string::npos) {
  105. result += s.substr(pos, s.size() - pos);
  106. break;
  107. }
  108. result += s.substr(pos, new_pos - pos) + replace;
  109. pos = new_pos;
  110. }
  111. s = std::move(result);
  112. }
  113. static void zeros(std::ofstream & file, size_t n) {
  114. char zero = 0;
  115. for (size_t i = 0; i < n; ++i) {
  116. file.write(&zero, 1);
  117. }
  118. }
  119. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  120. static std::string format(const char * fmt, ...) {
  121. va_list ap;
  122. va_list ap2;
  123. va_start(ap, fmt);
  124. va_copy(ap2, ap);
  125. int size = vsnprintf(NULL, 0, fmt, ap);
  126. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  127. std::vector<char> buf(size + 1);
  128. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  129. GGML_ASSERT(size2 == size);
  130. va_end(ap2);
  131. va_end(ap);
  132. return std::string(buf.data(), size);
  133. }
  134. //
  135. // gguf constants (sync with gguf.py)
  136. //
  137. enum llm_arch {
  138. LLM_ARCH_LLAMA,
  139. LLM_ARCH_FALCON,
  140. LLM_ARCH_GPT2,
  141. LLM_ARCH_GPTJ,
  142. LLM_ARCH_GPTNEOX,
  143. LLM_ARCH_MPT,
  144. LLM_ARCH_UNKNOWN,
  145. };
  146. static std::map<llm_arch, std::string> LLM_ARCH_NAMES = {
  147. { LLM_ARCH_LLAMA, "llama" },
  148. { LLM_ARCH_FALCON, "falcon" },
  149. { LLM_ARCH_GPT2, "gpt2" },
  150. { LLM_ARCH_GPTJ, "gptj" },
  151. { LLM_ARCH_GPTNEOX, "gptneox" },
  152. { LLM_ARCH_MPT, "mpt" },
  153. };
  154. enum llm_kv {
  155. LLM_KV_GENERAL_ARCHITECTURE,
  156. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  157. LLM_KV_GENERAL_ALIGNMENT,
  158. LLM_KV_GENERAL_NAME,
  159. LLM_KV_GENERAL_AUTHOR,
  160. LLM_KV_GENERAL_URL,
  161. LLM_KV_GENERAL_DESCRIPTION,
  162. LLM_KV_GENERAL_LICENSE,
  163. LLM_KV_GENERAL_SOURCE_URL,
  164. LLM_KV_GENERAL_SOURCE_HF_REPO,
  165. LLM_KV_CONTEXT_LENGTH,
  166. LLM_KV_EMBEDDING_LENGTH,
  167. LLM_KV_BLOCK_COUNT,
  168. LLM_KV_FEED_FORWARD_LENGTH,
  169. LLM_KV_USE_PARALLEL_RESIDUAL,
  170. LLM_KV_TENSOR_DATA_LAYOUT,
  171. LLM_KV_ATTENTION_HEAD_COUNT,
  172. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  173. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  174. LLM_KV_ATTENTION_CLAMP_KQV,
  175. LLM_KV_ATTENTION_LAYERNORM_EPS,
  176. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  177. LLM_KV_ROPE_DIMENSION_COUNT,
  178. LLM_KV_ROPE_FREQ_BASE,
  179. LLM_KV_ROPE_SCALE_LINEAR,
  180. LLM_KV_TOKENIZER_MODEL,
  181. LLM_KV_TOKENIZER_LIST,
  182. LLM_KV_TOKENIZER_TOKEN_TYPE,
  183. LLM_KV_TOKENIZER_SCORES,
  184. LLM_KV_TOKENIZER_MERGES,
  185. LLM_KV_TOKENIZER_BOS_ID,
  186. LLM_KV_TOKENIZER_EOS_ID,
  187. LLM_KV_TOKENIZER_UNK_ID,
  188. LLM_KV_TOKENIZER_SEP_ID,
  189. LLM_KV_TOKENIZER_PAD_ID,
  190. LLM_KV_TOKENIZER_HF_JSON,
  191. LLM_KV_TOKENIZER_RWKV,
  192. };
  193. static std::map<llm_kv, std::string> LLM_KV_NAMES = {
  194. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  195. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  196. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  197. { LLM_KV_GENERAL_NAME, "general.name" },
  198. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  199. { LLM_KV_GENERAL_URL, "general.url" },
  200. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  201. { LLM_KV_GENERAL_LICENSE, "general.license" },
  202. { LLM_KV_GENERAL_SOURCE_URL, "general.source_url" },
  203. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source_hf_repo" },
  204. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  205. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  206. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  207. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  208. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  209. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  210. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  211. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  212. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  213. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  214. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  215. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  216. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  217. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  218. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  219. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  220. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  221. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  222. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  223. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  224. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  225. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  226. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  227. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  228. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  229. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  230. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  231. };
  232. struct LLM_KV {
  233. LLM_KV(llm_arch arch) : arch(arch) {}
  234. llm_arch arch;
  235. std::string operator()(llm_kv kv) const {
  236. return ::format(LLM_KV_NAMES[kv].c_str(), LLM_ARCH_NAMES[arch].c_str());
  237. }
  238. };
  239. enum llm_tensor {
  240. LLM_TENSOR_TOKEN_EMBD,
  241. LLM_TENSOR_POS_EMBD,
  242. LLM_TENSOR_OUTPUT,
  243. LLM_TENSOR_OUTPUT_NORM,
  244. LLM_TENSOR_ROPE_FREQS,
  245. LLM_TENSOR_ATTN_Q,
  246. LLM_TENSOR_ATTN_K,
  247. LLM_TENSOR_ATTN_V,
  248. LLM_TENSOR_ATTN_QKV,
  249. LLM_TENSOR_ATTN_OUT,
  250. LLM_TENSOR_ATTN_NORM,
  251. LLM_TENSOR_ATTN_NORM_2,
  252. LLM_TENSOR_ATTN_ROT_EMBD,
  253. LLM_TENSOR_FFN_GATE,
  254. LLM_TENSOR_FFN_DOWN,
  255. LLM_TENSOR_FFN_UP,
  256. LLM_TENSOR_FFN_NORM,
  257. };
  258. static std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  259. {
  260. LLM_ARCH_LLAMA,
  261. {
  262. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  263. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  264. { LLM_TENSOR_OUTPUT, "output" },
  265. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  266. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  267. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  268. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  269. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  270. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  271. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  272. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  273. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  274. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  275. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  276. },
  277. },
  278. {
  279. LLM_ARCH_FALCON,
  280. {
  281. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  282. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  283. { LLM_TENSOR_OUTPUT, "output" },
  284. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  285. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  286. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  287. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  288. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  289. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  290. },
  291. },
  292. {
  293. LLM_ARCH_GPT2,
  294. {
  295. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  296. },
  297. },
  298. {
  299. LLM_ARCH_GPTJ,
  300. {
  301. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  302. },
  303. },
  304. {
  305. LLM_ARCH_GPTNEOX,
  306. {
  307. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  308. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  309. { LLM_TENSOR_OUTPUT, "output" },
  310. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  311. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  312. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  313. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  314. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  315. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  316. },
  317. },
  318. {
  319. LLM_ARCH_MPT,
  320. {
  321. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  322. },
  323. },
  324. {
  325. LLM_ARCH_UNKNOWN,
  326. {
  327. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  328. },
  329. },
  330. };
  331. static llm_arch llm_arch_from_string(const std::string & name) {
  332. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  333. if (kv.second == name) {
  334. return kv.first;
  335. }
  336. }
  337. return LLM_ARCH_UNKNOWN;
  338. }
  339. // helper to handle gguf constants
  340. // usage:
  341. //
  342. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  343. //
  344. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  345. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  346. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  347. //
  348. struct LLM_TN {
  349. LLM_TN(llm_arch arch) : arch(arch) {}
  350. llm_arch arch;
  351. std::string operator()(llm_tensor tensor) const {
  352. return LLM_TENSOR_NAMES[arch].at(tensor);
  353. }
  354. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  355. return LLM_TENSOR_NAMES[arch].at(tensor) + "." + suffix;
  356. }
  357. std::string operator()(llm_tensor tensor, int bid) const {
  358. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid);
  359. }
  360. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  361. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid) + "." + suffix;
  362. }
  363. };
  364. //
  365. // gguf helpers
  366. //
  367. #define GGUF_GET_KEY(ctx, dst, func, type, req, key) \
  368. { \
  369. const std::string skey(key); \
  370. const int kid = gguf_find_key(ctx, skey.c_str()); \
  371. if (kid >= 0) { \
  372. enum gguf_type ktype = gguf_get_kv_type(ctx, kid); \
  373. if (ktype != (type)) { \
  374. throw std::runtime_error(format("key %s has wrong type: %s", skey.c_str(), gguf_type_name(ktype))); \
  375. } \
  376. (dst) = func(ctx, kid); \
  377. } else if (req) { \
  378. throw std::runtime_error(format("key not found in model: %s", skey.c_str())); \
  379. } \
  380. }
  381. //
  382. // ggml helpers
  383. //
  384. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  385. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  386. if (plan.work_size > 0) {
  387. buf.resize(plan.work_size);
  388. plan.work_data = buf.data();
  389. }
  390. ggml_graph_compute(graph, &plan);
  391. }
  392. //
  393. // llama helpers
  394. //
  395. #ifdef GGML_USE_CUBLAS
  396. # define llama_host_malloc(n) ggml_cuda_host_malloc(n)
  397. # define llama_host_free(data) ggml_cuda_host_free(data)
  398. #elif GGML_USE_METAL
  399. # define llama_host_malloc(n) ggml_metal_host_malloc(n)
  400. # define llama_host_free(data) ggml_metal_host_free(data)
  401. #else
  402. # define llama_host_malloc(n) malloc(n)
  403. # define llama_host_free(data) free(data)
  404. #endif
  405. #if defined(_WIN32)
  406. static std::string llama_format_win_err(DWORD err) {
  407. LPSTR buf;
  408. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  409. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  410. if (!size) {
  411. return "FormatMessageA failed";
  412. }
  413. std::string ret(buf, size);
  414. LocalFree(buf);
  415. return ret;
  416. }
  417. #endif
  418. struct llama_buffer {
  419. void * data = NULL;
  420. size_t size = 0;
  421. // fallback to malloc / free
  422. // useful in cases where CUDA can try to allocate PINNED memory
  423. bool fallback = false;
  424. void resize(size_t n) {
  425. llama_host_free(data);
  426. data = llama_host_malloc(n);
  427. if (!data) {
  428. fallback = true;
  429. data = malloc(n);
  430. } else {
  431. fallback = false;
  432. }
  433. GGML_ASSERT(data);
  434. size = n;
  435. }
  436. ~llama_buffer() {
  437. if (data) {
  438. if (fallback) { // NOLINT
  439. free(data);
  440. } else {
  441. llama_host_free(data);
  442. }
  443. }
  444. data = NULL;
  445. }
  446. };
  447. struct llama_file {
  448. // use FILE * so we don't have to re-open the file to mmap
  449. FILE * fp;
  450. size_t size;
  451. llama_file(const char * fname, const char * mode) {
  452. fp = std::fopen(fname, mode);
  453. if (fp == NULL) {
  454. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  455. }
  456. seek(0, SEEK_END);
  457. size = tell();
  458. seek(0, SEEK_SET);
  459. }
  460. size_t tell() const {
  461. #ifdef _WIN32
  462. __int64 ret = _ftelli64(fp);
  463. #else
  464. long ret = std::ftell(fp);
  465. #endif
  466. GGML_ASSERT(ret != -1); // this really shouldn't fail
  467. return (size_t) ret;
  468. }
  469. void seek(size_t offset, int whence) const {
  470. #ifdef _WIN32
  471. int ret = _fseeki64(fp, (__int64) offset, whence);
  472. #else
  473. int ret = std::fseek(fp, (long) offset, whence);
  474. #endif
  475. GGML_ASSERT(ret == 0); // same
  476. }
  477. void read_raw(void * ptr, size_t len) const {
  478. if (len == 0) {
  479. return;
  480. }
  481. errno = 0;
  482. std::size_t ret = std::fread(ptr, len, 1, fp);
  483. if (ferror(fp)) {
  484. throw std::runtime_error(format("read error: %s", strerror(errno)));
  485. }
  486. if (ret != 1) {
  487. throw std::runtime_error(std::string("unexpectedly reached end of file"));
  488. }
  489. }
  490. uint32_t read_u32() const {
  491. uint32_t ret;
  492. read_raw(&ret, sizeof(ret));
  493. return ret;
  494. }
  495. void write_raw(const void * ptr, size_t len) const {
  496. if (len == 0) {
  497. return;
  498. }
  499. errno = 0;
  500. size_t ret = std::fwrite(ptr, len, 1, fp);
  501. if (ret != 1) {
  502. throw std::runtime_error(format("write error: %s", strerror(errno)));
  503. }
  504. }
  505. void write_u32(std::uint32_t val) const {
  506. write_raw(&val, sizeof(val));
  507. }
  508. ~llama_file() {
  509. if (fp) {
  510. std::fclose(fp);
  511. }
  512. }
  513. };
  514. struct llama_mmap {
  515. void * addr;
  516. size_t size;
  517. llama_mmap(const llama_mmap &) = delete;
  518. #ifdef _POSIX_MAPPED_FILES
  519. static constexpr bool SUPPORTED = true;
  520. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  521. size = file->size;
  522. int fd = fileno(file->fp);
  523. int flags = MAP_SHARED;
  524. // prefetch/readahead impairs performance on NUMA systems
  525. if (numa) { prefetch = 0; }
  526. #ifdef __linux__
  527. if (prefetch) { flags |= MAP_POPULATE; }
  528. #endif
  529. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  530. if (addr == MAP_FAILED) {
  531. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  532. }
  533. if (prefetch > 0) {
  534. // Advise the kernel to preload the mapped memory
  535. if (madvise(addr, std::min(file->size, prefetch), MADV_WILLNEED)) {
  536. fprintf(stderr, "warning: madvise(.., MADV_WILLNEED) failed: %s\n",
  537. strerror(errno));
  538. }
  539. }
  540. if (numa) {
  541. // advise the kernel not to use readahead
  542. // (because the next page might not belong on the same node)
  543. if (madvise(addr, file->size, MADV_RANDOM)) {
  544. fprintf(stderr, "warning: madvise(.., MADV_RANDOM) failed: %s\n",
  545. strerror(errno));
  546. }
  547. }
  548. }
  549. ~llama_mmap() {
  550. munmap(addr, size);
  551. }
  552. #elif defined(_WIN32)
  553. static constexpr bool SUPPORTED = true;
  554. llama_mmap(struct llama_file * file, bool prefetch = true, bool numa = false) {
  555. (void) numa;
  556. size = file->size;
  557. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  558. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  559. DWORD error = GetLastError();
  560. if (hMapping == NULL) {
  561. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  562. }
  563. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  564. error = GetLastError();
  565. CloseHandle(hMapping);
  566. if (addr == NULL) {
  567. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  568. }
  569. if (prefetch) {
  570. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  571. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  572. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  573. // may fail on pre-Windows 8 systems
  574. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  575. if (pPrefetchVirtualMemory) {
  576. // advise the kernel to preload the mapped memory
  577. WIN32_MEMORY_RANGE_ENTRY range;
  578. range.VirtualAddress = addr;
  579. range.NumberOfBytes = (SIZE_T)size;
  580. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  581. fprintf(stderr, "warning: PrefetchVirtualMemory failed: %s\n",
  582. llama_format_win_err(GetLastError()).c_str());
  583. }
  584. }
  585. }
  586. }
  587. ~llama_mmap() {
  588. if (!UnmapViewOfFile(addr)) {
  589. fprintf(stderr, "warning: UnmapViewOfFile failed: %s\n",
  590. llama_format_win_err(GetLastError()).c_str());
  591. }
  592. }
  593. #else
  594. static constexpr bool SUPPORTED = false;
  595. llama_mmap(struct llama_file * file, bool prefetch = true, bool numa = false) {
  596. (void) file;
  597. (void) prefetch;
  598. (void) numa;
  599. throw std::runtime_error(std::string("mmap not supported"));
  600. }
  601. #endif
  602. };
  603. // Represents some region of memory being locked using mlock or VirtualLock;
  604. // will automatically unlock on destruction.
  605. struct llama_mlock {
  606. void * addr = NULL;
  607. size_t size = 0;
  608. bool failed_already = false;
  609. llama_mlock() {}
  610. llama_mlock(const llama_mlock &) = delete;
  611. ~llama_mlock() {
  612. if (size) {
  613. raw_unlock(addr, size);
  614. }
  615. }
  616. void init(void * ptr) {
  617. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  618. addr = ptr;
  619. }
  620. void grow_to(size_t target_size) {
  621. GGML_ASSERT(addr);
  622. if (failed_already) {
  623. return;
  624. }
  625. size_t granularity = lock_granularity();
  626. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  627. if (target_size > size) {
  628. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  629. size = target_size;
  630. } else {
  631. failed_already = true;
  632. }
  633. }
  634. }
  635. #ifdef _POSIX_MEMLOCK_RANGE
  636. static constexpr bool SUPPORTED = true;
  637. static size_t lock_granularity() {
  638. return (size_t) sysconf(_SC_PAGESIZE);
  639. }
  640. #ifdef __APPLE__
  641. #define MLOCK_SUGGESTION \
  642. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  643. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MLOCK (ulimit -l).\n"
  644. #else
  645. #define MLOCK_SUGGESTION \
  646. "Try increasing RLIMIT_MLOCK ('ulimit -l' as root).\n"
  647. #endif
  648. bool raw_lock(const void * addr, size_t size) const {
  649. if (!mlock(addr, size)) {
  650. return true;
  651. }
  652. char* errmsg = std::strerror(errno);
  653. bool suggest = (errno == ENOMEM);
  654. // Check if the resource limit is fine after all
  655. struct rlimit lock_limit;
  656. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  657. suggest = false;
  658. }
  659. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  660. suggest = false;
  661. }
  662. fprintf(stderr, "warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  663. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  664. return false;
  665. }
  666. #undef MLOCK_SUGGESTION
  667. static void raw_unlock(void * addr, size_t size) {
  668. if (munlock(addr, size)) {
  669. fprintf(stderr, "warning: failed to munlock buffer: %s\n", std::strerror(errno));
  670. }
  671. }
  672. #elif defined(_WIN32)
  673. static constexpr bool SUPPORTED = true;
  674. static size_t lock_granularity() {
  675. SYSTEM_INFO si;
  676. GetSystemInfo(&si);
  677. return (size_t) si.dwPageSize;
  678. }
  679. bool raw_lock(void * ptr, size_t len) const {
  680. for (int tries = 1; ; tries++) {
  681. if (VirtualLock(ptr, len)) {
  682. return true;
  683. }
  684. if (tries == 2) {
  685. fprintf(stderr, "warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  686. len, size, llama_format_win_err(GetLastError()).c_str());
  687. return false;
  688. }
  689. // It failed but this was only the first try; increase the working
  690. // set size and try again.
  691. SIZE_T min_ws_size, max_ws_size;
  692. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  693. fprintf(stderr, "warning: GetProcessWorkingSetSize failed: %s\n",
  694. llama_format_win_err(GetLastError()).c_str());
  695. return false;
  696. }
  697. // Per MSDN: "The maximum number of pages that a process can lock
  698. // is equal to the number of pages in its minimum working set minus
  699. // a small overhead."
  700. // Hopefully a megabyte is enough overhead:
  701. size_t increment = len + 1048576;
  702. // The minimum must be <= the maximum, so we need to increase both:
  703. min_ws_size += increment;
  704. max_ws_size += increment;
  705. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  706. fprintf(stderr, "warning: SetProcessWorkingSetSize failed: %s\n",
  707. llama_format_win_err(GetLastError()).c_str());
  708. return false;
  709. }
  710. }
  711. }
  712. static void raw_unlock(void * ptr, size_t len) {
  713. if (!VirtualUnlock(ptr, len)) {
  714. fprintf(stderr, "warning: failed to VirtualUnlock buffer: %s\n",
  715. llama_format_win_err(GetLastError()).c_str());
  716. }
  717. }
  718. #else
  719. static constexpr bool SUPPORTED = false;
  720. static size_t lock_granularity() {
  721. return (size_t) 65536;
  722. }
  723. bool raw_lock(const void * addr, size_t len) const {
  724. fprintf(stderr, "warning: mlock not supported on this system\n");
  725. return false;
  726. }
  727. static void raw_unlock(const void * addr, size_t len) {}
  728. #endif
  729. };
  730. typedef void (*offload_func_t)(struct ggml_tensor * tensor);
  731. static void llama_nop(struct ggml_tensor * tensor) { // don't offload by default
  732. (void) tensor;
  733. }
  734. static std::string llama_token_to_str(const struct llama_context * ctx, llama_token token) {
  735. std::vector<char> result(8, 0);
  736. const int n_tokens = llama_token_to_piece(ctx, token, result.data(), result.size());
  737. if (n_tokens < 0) {
  738. result.resize(-n_tokens);
  739. int check = llama_token_to_piece(ctx, token, result.data(), result.size());
  740. GGML_ASSERT(check == -n_tokens);
  741. } else {
  742. result.resize(n_tokens);
  743. }
  744. return std::string(result.data(), result.size());
  745. }
  746. //
  747. // globals
  748. //
  749. struct llama_state {
  750. // We save the log callback globally
  751. llama_log_callback log_callback = llama_log_callback_default;
  752. void * log_callback_user_data = nullptr;
  753. };
  754. static llama_state g_state;
  755. // available llama models
  756. enum e_model {
  757. MODEL_UNKNOWN,
  758. MODEL_3B,
  759. MODEL_7B,
  760. MODEL_13B,
  761. MODEL_30B,
  762. MODEL_34B,
  763. MODEL_40B,
  764. MODEL_65B,
  765. MODEL_70B,
  766. };
  767. static const size_t kB = 1024;
  768. static const size_t MB = kB*kB;
  769. // default hparams (LLaMA 7B)
  770. struct llama_hparams {
  771. uint32_t n_vocab = 32000;
  772. uint32_t n_ctx_train = 2048; // the context size used during training
  773. uint32_t n_ctx = 512; // the context size used during inference
  774. uint32_t n_embd = 4096;
  775. uint32_t n_head = 32;
  776. uint32_t n_head_kv = 32;
  777. uint32_t n_layer = 32;
  778. uint32_t n_rot = 64;
  779. uint32_t n_ff = 11008;
  780. float f_norm_eps = 1e-5;
  781. float f_norm_rms_eps = 1e-5;
  782. float rope_freq_base = 10000.0f;
  783. float rope_freq_scale = 1.0f;
  784. bool operator!=(const llama_hparams & other) const {
  785. return static_cast<bool>(memcmp(this, &other, sizeof(llama_hparams))); // NOLINT
  786. }
  787. uint32_t n_gqa() const {
  788. return n_head/n_head_kv;
  789. }
  790. uint32_t n_embd_head() const {
  791. return n_embd/n_head;
  792. }
  793. uint32_t n_embd_gqa() const {
  794. return n_embd/n_gqa();
  795. }
  796. size_t kv_size() const {
  797. size_t result = 2ull;
  798. result *= (size_t) n_embd_gqa();
  799. result *= (size_t) n_ctx;
  800. result *= (size_t) n_layer;
  801. result *= sizeof(ggml_fp16_t);
  802. return result;
  803. }
  804. };
  805. struct llama_layer {
  806. // normalization
  807. struct ggml_tensor * attn_norm;
  808. struct ggml_tensor * attn_norm_b;
  809. struct ggml_tensor * attn_norm_2;
  810. struct ggml_tensor * attn_norm_2_b;
  811. // attention
  812. struct ggml_tensor * wq;
  813. struct ggml_tensor * wk;
  814. struct ggml_tensor * wv;
  815. struct ggml_tensor * wo;
  816. struct ggml_tensor * wqkv;
  817. // normalization
  818. struct ggml_tensor * ffn_norm;
  819. // ff
  820. struct ggml_tensor * w1; // ffn_gate
  821. struct ggml_tensor * w2; // ffn_down
  822. struct ggml_tensor * w3; // ffn_up
  823. };
  824. struct llama_kv_cache {
  825. struct ggml_tensor * k = NULL;
  826. struct ggml_tensor * v = NULL;
  827. struct ggml_context * ctx = NULL;
  828. llama_buffer buf;
  829. int n; // number of tokens currently in the cache
  830. ~llama_kv_cache() {
  831. if (ctx) {
  832. ggml_free(ctx);
  833. }
  834. #ifdef GGML_USE_CUBLAS
  835. ggml_cuda_free_data(k);
  836. ggml_cuda_free_data(v);
  837. #endif // GGML_USE_CUBLAS
  838. }
  839. };
  840. struct llama_vocab {
  841. using id = int32_t;
  842. using token = std::string;
  843. using ttype = llama_token_type;
  844. struct token_data {
  845. token text;
  846. float score;
  847. ttype type;
  848. };
  849. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  850. std::unordered_map<token, id> token_to_id;
  851. std::vector<token_data> id_to_token;
  852. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  853. // default LLaMA special tokens
  854. id special_bos_id = 1;
  855. id special_eos_id = 2;
  856. id special_unk_id = 0;
  857. id special_sep_id = -1;
  858. id special_pad_id = -1;
  859. id linefeed_id = 13;
  860. int find_bpe_rank(std::string token_left, std::string token_right) const {
  861. replace_all(token_left, " ", "\u0120");
  862. replace_all(token_left, "\n", "\u010A");
  863. replace_all(token_right, " ", "\u0120");
  864. replace_all(token_right, "\n", "\u010A");
  865. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  866. if (it == bpe_ranks.end()) {
  867. return -1;
  868. }
  869. return it->second;
  870. }
  871. };
  872. struct llama_model {
  873. e_model type = MODEL_UNKNOWN;
  874. llm_arch arch = LLM_ARCH_UNKNOWN;
  875. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  876. std::string name = "n/a";
  877. llama_hparams hparams;
  878. llama_vocab vocab;
  879. struct ggml_tensor * tok_embeddings;
  880. struct ggml_tensor * output_norm;
  881. struct ggml_tensor * output_norm_b;
  882. struct ggml_tensor * output;
  883. std::vector<llama_layer> layers;
  884. int n_gpu_layers;
  885. // context
  886. struct ggml_context * ctx = NULL;
  887. // the model memory buffer
  888. llama_buffer buf;
  889. // model memory mapped file
  890. std::unique_ptr<llama_mmap> mapping;
  891. // objects representing data potentially being locked in memory
  892. llama_mlock mlock_buf;
  893. llama_mlock mlock_mmap;
  894. // for quantize-stats only
  895. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  896. int64_t t_load_us = 0;
  897. int64_t t_start_us = 0;
  898. ~llama_model() {
  899. if (ctx) {
  900. ggml_free(ctx);
  901. }
  902. #ifdef GGML_USE_CUBLAS
  903. for (size_t i = 0; i < tensors_by_name.size(); ++i) {
  904. ggml_cuda_free_data(tensors_by_name[i].second);
  905. }
  906. ggml_cuda_free_scratch();
  907. #elif defined(GGML_USE_CLBLAST)
  908. for (size_t i = 0; i < tensors_by_name.size(); ++i) {
  909. ggml_cl_free_data(tensors_by_name[i].second);
  910. }
  911. #endif
  912. }
  913. };
  914. struct llama_context {
  915. llama_context(const llama_model & model) : model(model), t_load_us(model.t_load_us), t_start_us(model.t_start_us) {}
  916. ~llama_context() {
  917. if (model_owner) {
  918. delete &model;
  919. }
  920. #ifdef GGML_USE_METAL
  921. if (ctx_metal) {
  922. ggml_metal_free(ctx_metal);
  923. }
  924. #endif
  925. if (alloc) {
  926. ggml_allocr_free(alloc);
  927. }
  928. }
  929. std::mt19937 rng;
  930. bool has_evaluated_once = false;
  931. int64_t t_sample_us = 0;
  932. int64_t t_eval_us = 0;
  933. int64_t t_p_eval_us = 0;
  934. int32_t n_sample = 0; // number of tokens sampled
  935. int32_t n_eval = 0; // number of eval calls
  936. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  937. const llama_model & model;
  938. bool model_owner = false;
  939. int64_t t_load_us;
  940. int64_t t_start_us;
  941. // key + value cache for the self attention
  942. struct llama_kv_cache kv_self;
  943. // decode output (2-dimensional array: [n_tokens][n_vocab])
  944. std::vector<float> logits;
  945. bool logits_all = false;
  946. // input embedding (1-dimensional array: [n_embd])
  947. std::vector<float> embedding;
  948. // reusable buffer for `struct ggml_graph_plan.work_data`
  949. std::vector<uint8_t> work_buffer;
  950. // memory buffers used to evaluate the model
  951. llama_buffer buf_compute;
  952. llama_buffer buf_alloc;
  953. ggml_allocr * alloc = NULL;
  954. #ifdef GGML_USE_METAL
  955. ggml_metal_context * ctx_metal = NULL;
  956. #endif
  957. #ifdef GGML_USE_MPI
  958. ggml_mpi_context * ctx_mpi = NULL;
  959. #endif
  960. };
  961. //
  962. // kv cache helpers
  963. //
  964. static bool llama_kv_cache_init(
  965. const struct llama_hparams & hparams,
  966. struct llama_kv_cache & cache,
  967. ggml_type wtype,
  968. int n_ctx,
  969. int n_gpu_layers) {
  970. const int n_embd = hparams.n_embd_gqa();
  971. const int n_layer = hparams.n_layer;
  972. const int64_t n_mem = n_layer*n_ctx;
  973. const int64_t n_elements = n_embd*n_mem;
  974. cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
  975. cache.n = 0;
  976. struct ggml_init_params params;
  977. params.mem_size = cache.buf.size;
  978. params.mem_buffer = cache.buf.data;
  979. params.no_alloc = false;
  980. cache.ctx = ggml_init(params);
  981. if (!cache.ctx) {
  982. LLAMA_LOG_ERROR("%s: failed to allocate memory for kv cache\n", __func__);
  983. return false;
  984. }
  985. cache.k = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  986. cache.v = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  987. ggml_set_name(cache.k, "cache_k");
  988. ggml_set_name(cache.v, "cache_v");
  989. (void) n_gpu_layers;
  990. #ifdef GGML_USE_CUBLAS
  991. if (n_gpu_layers > n_layer + 1) {
  992. ggml_cuda_assign_buffers_no_scratch(cache.v);
  993. }
  994. if (n_gpu_layers > n_layer + 2) {
  995. ggml_cuda_assign_buffers_no_scratch(cache.k);
  996. }
  997. #endif // GGML_USE_CUBLAS
  998. return true;
  999. }
  1000. //
  1001. // model loading and saving
  1002. //
  1003. enum llama_fver {
  1004. GGUF_FILE_VERSION_V1 = 1,
  1005. GGUF_FILE_VERSION_V2 = 2,
  1006. };
  1007. static const char * llama_file_version_name(llama_fver version) {
  1008. switch (version) {
  1009. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  1010. case GGUF_FILE_VERSION_V2: return "GGUF V2 (latest)";
  1011. }
  1012. return "unknown";
  1013. }
  1014. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  1015. char buf[256];
  1016. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  1017. for (size_t i = 1; i < ne.size(); i++) {
  1018. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  1019. }
  1020. return buf;
  1021. }
  1022. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  1023. char buf[256];
  1024. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  1025. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  1026. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  1027. }
  1028. return buf;
  1029. }
  1030. struct llama_model_loader {
  1031. int n_kv = 0;
  1032. int n_tensors = 0;
  1033. int n_created = 0;
  1034. int64_t n_elements = 0;
  1035. bool use_mmap = false;
  1036. llama_file file;
  1037. llama_ftype ftype;
  1038. llama_fver fver;
  1039. std::unique_ptr<llama_mmap> mapping;
  1040. struct gguf_context * ctx_gguf = NULL;
  1041. struct ggml_context * ctx_meta = NULL;
  1042. llama_model_loader(const std::string & fname, bool use_mmap) : file(fname.c_str(), "rb") {
  1043. struct gguf_init_params params = {
  1044. /*.no_alloc = */ true,
  1045. /*.ctx = */ &ctx_meta,
  1046. };
  1047. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  1048. if (!ctx_gguf) {
  1049. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  1050. }
  1051. n_kv = gguf_get_n_kv(ctx_gguf);
  1052. n_tensors = gguf_get_n_tensors(ctx_gguf);
  1053. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  1054. for (int i = 0; i < n_tensors; i++) {
  1055. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  1056. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  1057. n_elements += ggml_nelements(t);
  1058. }
  1059. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  1060. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  1061. // determine file type based on the number of tensors for each quantization and print meta data
  1062. // TODO: make optional
  1063. {
  1064. std::map<enum ggml_type, uint32_t> n_type;
  1065. uint32_t n_type_max = 0;
  1066. enum ggml_type type_max = GGML_TYPE_F32;
  1067. for (int i = 0; i < n_tensors; i++) {
  1068. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  1069. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, name);
  1070. n_type[meta->type]++;
  1071. if (n_type_max < n_type[meta->type]) {
  1072. n_type_max = n_type[meta->type];
  1073. type_max = meta->type;
  1074. }
  1075. 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());
  1076. }
  1077. switch (type_max) {
  1078. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  1079. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  1080. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  1081. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  1082. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  1083. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  1084. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  1085. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  1086. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  1087. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  1088. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  1089. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  1090. default:
  1091. {
  1092. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  1093. ftype = LLAMA_FTYPE_ALL_F32;
  1094. } break;
  1095. }
  1096. // this is a way to mark that we have "guessed" the file type
  1097. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  1098. {
  1099. const int kid = gguf_find_key(ctx_gguf, "general.file_type");
  1100. if (kid >= 0) {
  1101. ftype = (llama_ftype) gguf_get_val_u32(ctx_gguf, kid);
  1102. }
  1103. }
  1104. for (int i = 0; i < n_kv; i++) {
  1105. const char * name = gguf_get_key(ctx_gguf, i);
  1106. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  1107. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-8s\n", __func__, i, name, gguf_type_name(type));
  1108. }
  1109. // print type counts
  1110. for (auto & kv : n_type) {
  1111. if (kv.second == 0) {
  1112. continue;
  1113. }
  1114. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  1115. }
  1116. }
  1117. if (!llama_mmap::SUPPORTED) {
  1118. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  1119. use_mmap = false;
  1120. }
  1121. this->use_mmap = use_mmap;
  1122. }
  1123. ~llama_model_loader() {
  1124. if (ctx_gguf) {
  1125. gguf_free(ctx_gguf);
  1126. }
  1127. if (ctx_meta) {
  1128. ggml_free(ctx_meta);
  1129. }
  1130. }
  1131. std::string get_arch_name() const {
  1132. const auto kv = LLM_KV(LLM_ARCH_UNKNOWN);
  1133. std::string arch_name;
  1134. GGUF_GET_KEY(ctx_gguf, arch_name, gguf_get_val_str, GGUF_TYPE_STRING, false, kv(LLM_KV_GENERAL_ARCHITECTURE));
  1135. return arch_name;
  1136. }
  1137. enum llm_arch get_arch() const {
  1138. const std::string arch_name = get_arch_name();
  1139. return llm_arch_from_string(arch_name);
  1140. }
  1141. const char * get_tensor_name(int i) const {
  1142. return gguf_get_tensor_name(ctx_gguf, i);
  1143. }
  1144. struct ggml_tensor * get_tensor_meta(int i) const {
  1145. return ggml_get_tensor(ctx_meta, get_tensor_name(i));
  1146. }
  1147. void calc_sizes(size_t & ctx_size_p, size_t & mmapped_size_p) const {
  1148. ctx_size_p = 0;
  1149. mmapped_size_p = 0;
  1150. for (int i = 0; i < n_tensors; i++) {
  1151. struct ggml_tensor * meta = get_tensor_meta(i);
  1152. ctx_size_p += sizeof(struct ggml_tensor) + GGML_OBJECT_SIZE;
  1153. (use_mmap ? mmapped_size_p : ctx_size_p) += ggml_nbytes_pad(meta);
  1154. }
  1155. }
  1156. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta, ggml_backend backend) {
  1157. if (backend != GGML_BACKEND_CPU) {
  1158. ggml_set_no_alloc(ctx, true);
  1159. }
  1160. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  1161. tensor->backend = backend; // TODO: ggml_set_backend
  1162. ggml_set_name(tensor, ggml_get_name(meta));
  1163. if (backend != GGML_BACKEND_CPU) {
  1164. ggml_set_no_alloc(ctx, use_mmap);
  1165. }
  1166. n_created++;
  1167. return tensor;
  1168. }
  1169. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, ggml_backend backend) {
  1170. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  1171. if (cur == NULL) {
  1172. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  1173. }
  1174. {
  1175. bool is_ok = true;
  1176. for (size_t i = 0; i < ne.size(); ++i) {
  1177. if (ne[i] != cur->ne[i]) {
  1178. is_ok = false;
  1179. break;
  1180. }
  1181. }
  1182. if (!is_ok) {
  1183. throw std::runtime_error(
  1184. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  1185. __func__, name.c_str(),
  1186. llama_format_tensor_shape(ne).c_str(),
  1187. llama_format_tensor_shape(cur).c_str()));
  1188. }
  1189. }
  1190. return create_tensor_for(ctx, cur, backend);
  1191. }
  1192. void done_getting_tensors() const {
  1193. if (n_created != n_tensors) {
  1194. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  1195. }
  1196. }
  1197. size_t file_offset(const char * name) const {
  1198. const int idx = gguf_find_tensor(ctx_gguf, name);
  1199. if (idx < 0) {
  1200. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  1201. }
  1202. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  1203. }
  1204. void load_data_for(struct ggml_tensor * cur) const {
  1205. const size_t offs = file_offset(ggml_get_name(cur));
  1206. if (use_mmap) {
  1207. cur->data = (uint8_t *) mapping->addr + offs;
  1208. } else {
  1209. file.seek(offs, SEEK_SET);
  1210. file.read_raw(cur->data, ggml_nbytes(cur));
  1211. }
  1212. }
  1213. void load_all_data(struct ggml_context * ctx, llama_progress_callback progress_callback, void * progress_callback_user_data, llama_mlock * lmlock) {
  1214. size_t size_data = 0;
  1215. size_t size_lock = 0;
  1216. size_t size_pref = 0; // prefetch
  1217. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  1218. struct ggml_tensor * cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
  1219. size_data += ggml_nbytes(cur);
  1220. if (cur->backend == GGML_BACKEND_CPU) {
  1221. size_pref += ggml_nbytes(cur);
  1222. }
  1223. }
  1224. if (use_mmap) {
  1225. mapping.reset(new llama_mmap(&file, size_pref, ggml_is_numa()));
  1226. if (lmlock) {
  1227. lmlock->init(mapping->addr);
  1228. }
  1229. }
  1230. size_t done_size = 0;
  1231. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  1232. struct ggml_tensor * cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
  1233. GGML_ASSERT(cur); // unused tensors should have been caught by load_data already
  1234. if (progress_callback) {
  1235. progress_callback((float) done_size / size_data, progress_callback_user_data);
  1236. }
  1237. // allocate temp buffer if not using mmap
  1238. if (!use_mmap && cur->data == NULL) {
  1239. GGML_ASSERT(cur->backend != GGML_BACKEND_CPU);
  1240. cur->data = malloc(ggml_nbytes(cur));
  1241. }
  1242. load_data_for(cur);
  1243. switch (cur->backend) {
  1244. case GGML_BACKEND_CPU:
  1245. if (use_mmap && lmlock) {
  1246. size_lock += ggml_nbytes(cur);
  1247. lmlock->grow_to(size_lock);
  1248. }
  1249. break;
  1250. #if defined(GGML_USE_CUBLAS)
  1251. case GGML_BACKEND_GPU:
  1252. case GGML_BACKEND_GPU_SPLIT:
  1253. // old code:
  1254. //ggml_cuda_transform_tensor(lt.data, lt.ggml_tensor);
  1255. // TODO: test if this works !!
  1256. ggml_cuda_transform_tensor(cur->data, cur);
  1257. if (!use_mmap) {
  1258. free(cur->data);
  1259. }
  1260. break;
  1261. #elif defined(GGML_USE_CLBLAST)
  1262. case GGML_BACKEND_GPU:
  1263. ggml_cl_transform_tensor(cur->data, cur);
  1264. if (!use_mmap) {
  1265. free(cur->data);
  1266. }
  1267. break;
  1268. #endif
  1269. default:
  1270. continue;
  1271. }
  1272. done_size += ggml_nbytes(cur);
  1273. }
  1274. }
  1275. };
  1276. //
  1277. // load LLaMA models
  1278. //
  1279. std::string llama_model_ftype_name(enum llama_ftype ftype) {
  1280. if (ftype & LLAMA_FTYPE_GUESSED) {
  1281. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  1282. }
  1283. switch (ftype) {
  1284. case LLAMA_FTYPE_ALL_F32: return "all F32";
  1285. case LLAMA_FTYPE_MOSTLY_F16: return "mostly F16";
  1286. case LLAMA_FTYPE_MOSTLY_Q4_0: return "mostly Q4_0";
  1287. case LLAMA_FTYPE_MOSTLY_Q4_1: return "mostly Q4_1";
  1288. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  1289. return "mostly Q4_1, some F16";
  1290. case LLAMA_FTYPE_MOSTLY_Q5_0: return "mostly Q5_0";
  1291. case LLAMA_FTYPE_MOSTLY_Q5_1: return "mostly Q5_1";
  1292. case LLAMA_FTYPE_MOSTLY_Q8_0: return "mostly Q8_0";
  1293. // K-quants
  1294. case LLAMA_FTYPE_MOSTLY_Q2_K: return "mostly Q2_K";
  1295. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "mostly Q3_K - Small";
  1296. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "mostly Q3_K - Medium";
  1297. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "mostly Q3_K - Large";
  1298. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "mostly Q4_K - Small";
  1299. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "mostly Q4_K - Medium";
  1300. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "mostly Q5_K - Small";
  1301. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "mostly Q5_K - Medium";
  1302. case LLAMA_FTYPE_MOSTLY_Q6_K: return "mostly Q6_K";
  1303. default: return "unknown, may not work";
  1304. }
  1305. }
  1306. static const char * llama_model_type_name(e_model type) {
  1307. switch (type) {
  1308. case MODEL_3B: return "3B";
  1309. case MODEL_7B: return "7B";
  1310. case MODEL_13B: return "13B";
  1311. case MODEL_30B: return "30B";
  1312. case MODEL_34B: return "34B";
  1313. case MODEL_40B: return "40B";
  1314. case MODEL_65B: return "65B";
  1315. case MODEL_70B: return "70B";
  1316. default: return "?B";
  1317. }
  1318. }
  1319. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  1320. model.arch = ml.get_arch();
  1321. if (model.arch == LLM_ARCH_UNKNOWN) {
  1322. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  1323. }
  1324. }
  1325. static void llm_load_hparams(
  1326. llama_model_loader & ml,
  1327. llama_model & model,
  1328. int n_ctx,
  1329. float rope_freq_base,
  1330. float rope_freq_scale) {
  1331. struct gguf_context * ctx = ml.ctx_gguf;
  1332. const auto kv = LLM_KV(model.arch);
  1333. auto & hparams = model.hparams;
  1334. // get general kv
  1335. GGUF_GET_KEY(ctx, model.name, gguf_get_val_str, GGUF_TYPE_STRING, false, kv(LLM_KV_GENERAL_NAME));
  1336. // get hparams kv
  1337. GGUF_GET_KEY(ctx, hparams.n_vocab, gguf_get_arr_n, GGUF_TYPE_ARRAY, true, kv(LLM_KV_TOKENIZER_LIST));
  1338. GGUF_GET_KEY(ctx, hparams.n_ctx_train, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_CONTEXT_LENGTH));
  1339. GGUF_GET_KEY(ctx, hparams.n_embd, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_EMBEDDING_LENGTH));
  1340. GGUF_GET_KEY(ctx, hparams.n_ff, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_FEED_FORWARD_LENGTH));
  1341. GGUF_GET_KEY(ctx, hparams.n_head, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_ATTENTION_HEAD_COUNT));
  1342. GGUF_GET_KEY(ctx, hparams.n_layer, gguf_get_val_u32, GGUF_TYPE_UINT32, true, kv(LLM_KV_BLOCK_COUNT));
  1343. // n_head_kv is optional, default to n_head
  1344. hparams.n_head_kv = hparams.n_head;
  1345. GGUF_GET_KEY(ctx, hparams.n_head_kv, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_ATTENTION_HEAD_COUNT_KV));
  1346. // TODO: manually setting rope freq base and scale should override this
  1347. // FIXME: partial fix when the param specified is not the default value, but
  1348. // will not work for overriding the model value to the params default
  1349. llama_context_params defaults = llama_context_default_params();
  1350. // rope_freq_base
  1351. {
  1352. float ropebase = 10000.0f;
  1353. GGUF_GET_KEY(ctx, ropebase, gguf_get_val_f32, GGUF_TYPE_FLOAT32, false, kv(LLM_KV_ROPE_FREQ_BASE));
  1354. if (ropebase != 10000.0f && rope_freq_base == defaults.rope_freq_base) {
  1355. rope_freq_base = ropebase;
  1356. }
  1357. }
  1358. // rope_freq_scale (inverse of the kv) is optional
  1359. {
  1360. float ropescale = 1.0f;
  1361. GGUF_GET_KEY(ctx, ropescale, gguf_get_val_f32, GGUF_TYPE_FLOAT32, false, kv(LLM_KV_ROPE_SCALE_LINEAR));
  1362. if (ropescale != 1.0f && rope_freq_scale == defaults.rope_freq_scale) {
  1363. rope_freq_scale = 1.0f/ropescale;
  1364. }
  1365. }
  1366. // sanity check for n_rot (optional)
  1367. {
  1368. hparams.n_rot = hparams.n_embd / hparams.n_head;
  1369. GGUF_GET_KEY(ctx, hparams.n_rot, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_ROPE_DIMENSION_COUNT));
  1370. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  1371. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  1372. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  1373. }
  1374. }
  1375. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  1376. // gpt-j n_rot = rotary_dim
  1377. }
  1378. // arch-specific KVs
  1379. switch (model.arch) {
  1380. case LLM_ARCH_LLAMA:
  1381. {
  1382. GGUF_GET_KEY(ctx, hparams.f_norm_rms_eps, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, kv(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS));
  1383. switch (hparams.n_layer) {
  1384. case 26: model.type = e_model::MODEL_3B; break;
  1385. case 32: model.type = e_model::MODEL_7B; break;
  1386. case 40: model.type = e_model::MODEL_13B; break;
  1387. case 48: model.type = e_model::MODEL_34B; break;
  1388. case 60: model.type = e_model::MODEL_30B; break;
  1389. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  1390. default: model.type = e_model::MODEL_UNKNOWN;
  1391. }
  1392. } break;
  1393. case LLM_ARCH_FALCON:
  1394. {
  1395. GGUF_GET_KEY(ctx, hparams.f_norm_eps, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, kv(LLM_KV_ATTENTION_LAYERNORM_EPS));
  1396. switch (hparams.n_layer) {
  1397. case 32: model.type = e_model::MODEL_7B; break;
  1398. case 60: model.type = e_model::MODEL_40B; break;
  1399. default: model.type = e_model::MODEL_UNKNOWN;
  1400. }
  1401. } break;
  1402. default: (void)0;
  1403. };
  1404. model.ftype = ml.ftype;
  1405. hparams.n_ctx = n_ctx;
  1406. hparams.rope_freq_base = rope_freq_base;
  1407. hparams.rope_freq_scale = rope_freq_scale;
  1408. }
  1409. // TODO: This should probably be in llama.h
  1410. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos);
  1411. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  1412. static void llm_load_vocab(
  1413. llama_model_loader & ml,
  1414. llama_model & model) {
  1415. auto & vocab = model.vocab;
  1416. struct gguf_context * ctx = ml.ctx_gguf;
  1417. const auto kv = LLM_KV(model.arch);
  1418. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  1419. if (token_idx == -1) {
  1420. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  1421. }
  1422. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  1423. if (score_idx == -1) {
  1424. throw std::runtime_error("cannot find tokenizer scores in model file\n");
  1425. }
  1426. const float * scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  1427. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  1428. if (toktype_idx == -1) {
  1429. throw std::runtime_error("cannot find token type list in GGUF file\n");
  1430. }
  1431. const int * toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  1432. // determine vocab type
  1433. {
  1434. std::string tokenizer_name;
  1435. GGUF_GET_KEY(ctx, tokenizer_name, gguf_get_val_str, GGUF_TYPE_STRING, true, kv(LLM_KV_TOKENIZER_MODEL));
  1436. if (tokenizer_name == "llama") {
  1437. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  1438. // default special tokens
  1439. vocab.special_bos_id = 1;
  1440. vocab.special_eos_id = 2;
  1441. vocab.special_unk_id = 0;
  1442. vocab.special_sep_id = -1;
  1443. vocab.special_pad_id = -1;
  1444. } else if (tokenizer_name == "gpt2") {
  1445. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  1446. // read bpe merges and populate bpe ranks
  1447. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  1448. if (merges_keyidx == -1) {
  1449. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  1450. }
  1451. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  1452. for (int i = 0; i < n_merges; i++) {
  1453. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  1454. std::string first;
  1455. std::string second;
  1456. const size_t pos = word.find(' ', 1);
  1457. if (pos != std::string::npos) {
  1458. first = word.substr(0, pos);
  1459. second = word.substr(pos + 1);
  1460. }
  1461. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  1462. }
  1463. // default special tokens
  1464. vocab.special_bos_id = 11;
  1465. vocab.special_eos_id = 11;
  1466. vocab.special_unk_id = -1;
  1467. vocab.special_sep_id = -1;
  1468. vocab.special_pad_id = -1;
  1469. } else {
  1470. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  1471. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  1472. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  1473. }
  1474. }
  1475. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  1476. vocab.id_to_token.resize(n_vocab);
  1477. for (uint32_t i = 0; i < n_vocab; i++) {
  1478. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  1479. vocab.token_to_id[word] = i;
  1480. auto & token_data = vocab.id_to_token[i];
  1481. token_data.text = std::move(word);
  1482. token_data.score = scores[i];
  1483. token_data.type = (llama_token_type) toktypes[i];
  1484. }
  1485. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  1486. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  1487. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  1488. } else {
  1489. vocab.linefeed_id = llama_tokenize_internal(vocab, "\n", false)[0];
  1490. }
  1491. // special tokens
  1492. GGUF_GET_KEY(ctx, vocab.special_bos_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_BOS_ID));
  1493. GGUF_GET_KEY(ctx, vocab.special_eos_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_EOS_ID));
  1494. GGUF_GET_KEY(ctx, vocab.special_unk_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_UNK_ID));
  1495. GGUF_GET_KEY(ctx, vocab.special_sep_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_SEP_ID));
  1496. GGUF_GET_KEY(ctx, vocab.special_pad_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, kv(LLM_KV_TOKENIZER_PAD_ID));
  1497. }
  1498. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  1499. const auto & hparams = model.hparams;
  1500. const auto & vocab = model.vocab;
  1501. // hparams
  1502. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  1503. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch).c_str());
  1504. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, vocab.type == LLAMA_VOCAB_TYPE_SPM ? "SPM" : "BPE"); // TODO: fix
  1505. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  1506. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  1507. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  1508. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, hparams.n_ctx);
  1509. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  1510. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  1511. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  1512. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  1513. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot); // a.k.a. n_embd_head, n_head_dim
  1514. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  1515. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  1516. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  1517. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  1518. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, hparams.rope_freq_base);
  1519. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, hparams.rope_freq_scale);
  1520. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  1521. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  1522. LLAMA_LOG_INFO("%s: model size = %.2f B\n", __func__, ml.n_elements*1e-9);
  1523. // general kv
  1524. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  1525. // special tokens
  1526. 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() ); }
  1527. 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() ); }
  1528. 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() ); }
  1529. 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() ); }
  1530. 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() ); }
  1531. 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() ); }
  1532. }
  1533. static void llm_load_tensors(
  1534. llama_model_loader & ml,
  1535. llama_model & model,
  1536. int n_batch,
  1537. int n_gpu_layers,
  1538. int main_gpu,
  1539. const float * tensor_split,
  1540. const bool mul_mat_q,
  1541. bool low_vram,
  1542. ggml_type memory_type,
  1543. bool use_mlock,
  1544. llama_progress_callback progress_callback,
  1545. void * progress_callback_user_data) {
  1546. model.t_start_us = ggml_time_us();
  1547. auto & ctx = model.ctx;
  1548. auto & hparams = model.hparams;
  1549. model.n_gpu_layers = n_gpu_layers;
  1550. size_t ctx_size;
  1551. size_t mmapped_size;
  1552. ml.calc_sizes(ctx_size, mmapped_size);
  1553. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MB\n", __func__, ctx_size/1024.0/1024.0);
  1554. // create the ggml context
  1555. {
  1556. model.buf.resize(ctx_size);
  1557. if (use_mlock) {
  1558. model.mlock_buf.init (model.buf.data);
  1559. model.mlock_buf.grow_to(model.buf.size);
  1560. }
  1561. struct ggml_init_params params = {
  1562. /*.mem_size =*/ model.buf.size,
  1563. /*.mem_buffer =*/ model.buf.data,
  1564. /*.no_alloc =*/ ml.use_mmap,
  1565. };
  1566. model.ctx = ggml_init(params);
  1567. if (!model.ctx) {
  1568. throw std::runtime_error(format("ggml_init() failed"));
  1569. }
  1570. }
  1571. (void) main_gpu;
  1572. (void) mul_mat_q;
  1573. #if defined(GGML_USE_CUBLAS)
  1574. LLAMA_LOG_INFO("%s: using " GGML_CUDA_NAME " for GPU acceleration\n", __func__);
  1575. ggml_cuda_set_main_device(main_gpu);
  1576. ggml_cuda_set_mul_mat_q(mul_mat_q);
  1577. #define LLAMA_BACKEND_OFFLOAD GGML_BACKEND_GPU
  1578. #define LLAMA_BACKEND_OFFLOAD_SPLIT GGML_BACKEND_GPU_SPLIT
  1579. #elif defined(GGML_USE_CLBLAST)
  1580. LLAMA_LOG_INFO("%s: using OpenCL for GPU acceleration\n", __func__);
  1581. #define LLAMA_BACKEND_OFFLOAD GGML_BACKEND_GPU
  1582. #define LLAMA_BACKEND_OFFLOAD_SPLIT GGML_BACKEND_GPU
  1583. #else
  1584. #define LLAMA_BACKEND_OFFLOAD GGML_BACKEND_CPU
  1585. #define LLAMA_BACKEND_OFFLOAD_SPLIT GGML_BACKEND_CPU
  1586. #endif
  1587. // prepare memory for the weights
  1588. size_t vram_weights = 0;
  1589. {
  1590. const int64_t n_embd = hparams.n_embd;
  1591. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  1592. const int64_t n_layer = hparams.n_layer;
  1593. const int64_t n_vocab = hparams.n_vocab;
  1594. const auto tn = LLM_TN(model.arch);
  1595. switch (model.arch) {
  1596. case LLM_ARCH_LLAMA:
  1597. {
  1598. model.tok_embeddings = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  1599. // output
  1600. {
  1601. ggml_backend backend_norm;
  1602. ggml_backend backend_output;
  1603. if (n_gpu_layers > int(n_layer)) {
  1604. // norm is not performance relevant on its own but keeping it in VRAM reduces data copying
  1605. // on Windows however this is detrimental unless everything is on the GPU
  1606. #ifndef _WIN32
  1607. backend_norm = low_vram ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  1608. #else
  1609. backend_norm = low_vram || n_gpu_layers <= (int) n_layer + 2 ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  1610. #endif // _WIN32
  1611. backend_output = LLAMA_BACKEND_OFFLOAD_SPLIT;
  1612. } else {
  1613. backend_norm = GGML_BACKEND_CPU;
  1614. backend_output = GGML_BACKEND_CPU;
  1615. }
  1616. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  1617. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  1618. if (backend_norm == GGML_BACKEND_GPU) {
  1619. vram_weights += ggml_nbytes(model.output_norm);
  1620. }
  1621. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  1622. vram_weights += ggml_nbytes(model.output);
  1623. }
  1624. }
  1625. const uint32_t n_ff = hparams.n_ff;
  1626. const int i_gpu_start = n_layer - n_gpu_layers;
  1627. model.layers.resize(n_layer);
  1628. for (uint32_t i = 0; i < n_layer; ++i) {
  1629. const ggml_backend backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD; // NOLINT
  1630. const ggml_backend backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD_SPLIT; // NOLINT
  1631. auto & layer = model.layers[i];
  1632. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  1633. layer.wq = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, backend_split);
  1634. layer.wk = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, backend_split);
  1635. layer.wv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, backend_split);
  1636. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  1637. layer.ffn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, backend);
  1638. layer.w1 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, backend_split);
  1639. layer.w2 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, backend_split);
  1640. layer.w3 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  1641. if (backend == GGML_BACKEND_GPU) {
  1642. vram_weights +=
  1643. ggml_nbytes(layer.attn_norm) + ggml_nbytes(layer.wq) + ggml_nbytes(layer.wk) +
  1644. ggml_nbytes(layer.wv) + ggml_nbytes(layer.wo) + ggml_nbytes(layer.ffn_norm) +
  1645. ggml_nbytes(layer.w1) + ggml_nbytes(layer.w2) + ggml_nbytes(layer.w3);
  1646. }
  1647. }
  1648. } break;
  1649. case LLM_ARCH_FALCON:
  1650. {
  1651. // TODO: CPU-only for now
  1652. model.tok_embeddings = ml.create_tensor(ctx, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, GGML_BACKEND_CPU);
  1653. // output
  1654. {
  1655. ggml_backend backend_norm;
  1656. ggml_backend backend_output;
  1657. if (n_gpu_layers > int(n_layer)) {
  1658. // norm is not performance relevant on its own but keeping it in VRAM reduces data copying
  1659. // on Windows however this is detrimental unless everything is on the GPU
  1660. #ifndef _WIN32
  1661. backend_norm = low_vram ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  1662. #else
  1663. backend_norm = low_vram || n_gpu_layers <= (int) n_layer + 2 ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  1664. #endif // _WIN32
  1665. backend_output = LLAMA_BACKEND_OFFLOAD_SPLIT;
  1666. } else {
  1667. backend_norm = GGML_BACKEND_CPU;
  1668. backend_output = GGML_BACKEND_CPU;
  1669. }
  1670. model.output_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, backend_norm);
  1671. model.output_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, backend_norm);
  1672. model.output = ml.create_tensor(ctx, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, backend_output);
  1673. if (backend_norm == GGML_BACKEND_GPU) {
  1674. vram_weights += ggml_nbytes(model.output_norm);
  1675. vram_weights += ggml_nbytes(model.output_norm_b);
  1676. }
  1677. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  1678. vram_weights += ggml_nbytes(model.output);
  1679. }
  1680. }
  1681. const uint32_t n_ff = hparams.n_ff;
  1682. const int i_gpu_start = n_layer - n_gpu_layers;
  1683. model.layers.resize(n_layer);
  1684. for (uint32_t i = 0; i < n_layer; ++i) {
  1685. const ggml_backend backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD; // NOLINT
  1686. const ggml_backend backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD_SPLIT; // NOLINT
  1687. auto & layer = model.layers[i];
  1688. layer.attn_norm = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, backend);
  1689. layer.attn_norm_b = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, backend);
  1690. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  1691. layer.attn_norm_2 = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, backend);
  1692. layer.attn_norm_2_b = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, backend);
  1693. if (backend == GGML_BACKEND_GPU) {
  1694. vram_weights += ggml_nbytes(layer.attn_norm_2);
  1695. vram_weights += ggml_nbytes(layer.attn_norm_2_b);
  1696. }
  1697. }
  1698. layer.wqkv = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, backend_split);
  1699. layer.wo = ml.create_tensor(ctx, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, backend_split);
  1700. layer.w2 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, backend_split);
  1701. layer.w3 = ml.create_tensor(ctx, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, backend_split);
  1702. if (backend == GGML_BACKEND_GPU) {
  1703. vram_weights +=
  1704. ggml_nbytes(layer.attn_norm) + ggml_nbytes(layer.attn_norm_b) +
  1705. ggml_nbytes(layer.wqkv) + ggml_nbytes(layer.wo) +
  1706. ggml_nbytes(layer.w2) + ggml_nbytes(layer.w3);
  1707. }
  1708. }
  1709. } break;
  1710. default:
  1711. throw std::runtime_error("unknown architecture");
  1712. };
  1713. }
  1714. ml.done_getting_tensors();
  1715. // print memory requirements
  1716. {
  1717. const size_t scale = memory_type == GGML_TYPE_F32 ? 2 : 1;
  1718. // this is the total memory required to run the inference
  1719. size_t mem_required =
  1720. ctx_size +
  1721. mmapped_size - vram_weights; // weights in VRAM not in memory
  1722. // this is the memory required by one llama_state
  1723. const size_t mem_required_state = scale*hparams.kv_size();
  1724. LLAMA_LOG_INFO("%s: mem required = %7.2f MB (+ %7.2f MB per state)\n", __func__,
  1725. mem_required / 1024.0 / 1024.0, mem_required_state / 1024.0 / 1024.0);
  1726. (void) n_batch;
  1727. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST)
  1728. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  1729. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  1730. if (n_gpu_layers > (int) hparams.n_layer) {
  1731. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  1732. }
  1733. size_t vram_kv_cache = 0;
  1734. #ifdef GGML_USE_CUBLAS
  1735. const int max_backend_supported_layers = hparams.n_layer + 3;
  1736. const int max_offloadable_layers = low_vram ? hparams.n_layer + 1 : hparams.n_layer + 3;
  1737. if (n_gpu_layers > (int) hparams.n_layer + 1) {
  1738. if (low_vram) {
  1739. LLAMA_LOG_INFO("%s: cannot offload v cache to GPU due to low VRAM option\n", __func__);
  1740. } else {
  1741. LLAMA_LOG_INFO("%s: offloading v cache to GPU\n", __func__);
  1742. vram_kv_cache += hparams.kv_size() / 2;
  1743. }
  1744. }
  1745. if (n_gpu_layers > (int) hparams.n_layer + 2) {
  1746. if (low_vram) {
  1747. LLAMA_LOG_WARN("%s: cannot offload k cache to GPU due to low VRAM option\n", __func__);
  1748. } else {
  1749. LLAMA_LOG_INFO("%s: offloading k cache to GPU\n", __func__);
  1750. vram_kv_cache += hparams.kv_size() / 2;
  1751. }
  1752. }
  1753. #elif defined(GGML_USE_CLBLAST)
  1754. const int max_backend_supported_layers = hparams.n_layer + 1;
  1755. const int max_offloadable_layers = hparams.n_layer + 1;
  1756. #endif // GGML_USE_CUBLAS
  1757. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n",
  1758. __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  1759. LLAMA_LOG_INFO("%s: VRAM used: %zu MB\n",
  1760. __func__, (vram_weights + vram_kv_cache + MB - 1) / MB); // round up
  1761. #else
  1762. (void) n_gpu_layers;
  1763. #endif // defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST)
  1764. }
  1765. // populate `tensors_by_name`
  1766. for (int i = 0; i < ml.n_tensors; ++i) {
  1767. struct ggml_tensor * cur = ggml_get_tensor(ctx, ml.get_tensor_name(i));
  1768. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  1769. }
  1770. (void) tensor_split;
  1771. #if defined(GGML_USE_CUBLAS)
  1772. {
  1773. ggml_cuda_set_tensor_split(tensor_split);
  1774. }
  1775. #endif
  1776. ml.load_all_data(ctx, progress_callback, progress_callback_user_data, use_mlock ? &model.mlock_mmap : NULL);
  1777. if (progress_callback) {
  1778. progress_callback(1.0f, progress_callback_user_data);
  1779. }
  1780. model.mapping = std::move(ml.mapping);
  1781. // loading time will be recalculate after the first eval, so
  1782. // we take page faults deferred by mmap() into consideration
  1783. model.t_load_us = ggml_time_us() - model.t_start_us;
  1784. }
  1785. static bool llama_model_load(
  1786. const std::string & fname,
  1787. llama_model & model,
  1788. int n_ctx,
  1789. int n_batch,
  1790. int n_gpu_layers,
  1791. int main_gpu,
  1792. const float * tensor_split,
  1793. const bool mul_mat_q,
  1794. float rope_freq_base,
  1795. float rope_freq_scale,
  1796. bool low_vram,
  1797. ggml_type memory_type,
  1798. bool use_mmap,
  1799. bool use_mlock,
  1800. bool vocab_only,
  1801. llama_progress_callback progress_callback,
  1802. void *progress_callback_user_data) {
  1803. try {
  1804. std::unique_ptr<llama_model_loader> ml(new llama_model_loader(fname, use_mmap));
  1805. llm_load_arch (*ml, model);
  1806. llm_load_hparams(*ml, model, n_ctx, rope_freq_base, rope_freq_scale);
  1807. llm_load_vocab (*ml, model);
  1808. llm_load_print_meta(*ml, model);
  1809. if (model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  1810. throw std::runtime_error("vocab size mismatch");
  1811. }
  1812. if (vocab_only) {
  1813. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  1814. return true;
  1815. }
  1816. llm_load_tensors(
  1817. *ml, model, n_batch, n_gpu_layers,
  1818. main_gpu, tensor_split, mul_mat_q, low_vram, memory_type,
  1819. use_mlock, progress_callback, progress_callback_user_data);
  1820. } catch (const std::exception & err) {
  1821. LLAMA_LOG_ERROR("error loading model: %s\n", err.what());
  1822. return false;
  1823. }
  1824. return true;
  1825. }
  1826. static struct ggml_cgraph * llm_build_llama(
  1827. llama_context & lctx,
  1828. const llama_token * tokens,
  1829. const float * embd,
  1830. int n_tokens,
  1831. int n_past) {
  1832. GGML_ASSERT((!tokens && embd) || (tokens && !embd)); // NOLINT
  1833. const int N = n_tokens;
  1834. const auto & model = lctx.model;
  1835. const auto & hparams = model.hparams;
  1836. const auto & kv_self = lctx.kv_self;
  1837. GGML_ASSERT(!!kv_self.ctx);
  1838. const int64_t n_embd = hparams.n_embd;
  1839. const int64_t n_layer = hparams.n_layer;
  1840. const int64_t n_ctx = hparams.n_ctx;
  1841. const int64_t n_head = hparams.n_head;
  1842. const int64_t n_head_kv = hparams.n_head_kv;
  1843. const int64_t n_embd_head = hparams.n_embd_head();
  1844. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  1845. GGML_ASSERT(n_embd_head == hparams.n_rot);
  1846. const float freq_base = hparams.rope_freq_base;
  1847. const float freq_scale = hparams.rope_freq_scale;
  1848. const float norm_rms_eps = hparams.f_norm_rms_eps;
  1849. const int n_gpu_layers = model.n_gpu_layers;
  1850. auto & buf_compute = lctx.buf_compute;
  1851. struct ggml_init_params params = {
  1852. /*.mem_size =*/ buf_compute.size,
  1853. /*.mem_buffer =*/ buf_compute.data,
  1854. /*.no_alloc =*/ false,
  1855. };
  1856. params.no_alloc = true;
  1857. struct ggml_context * ctx0 = ggml_init(params);
  1858. ggml_cgraph * gf = ggml_new_graph(ctx0);
  1859. struct ggml_tensor * cur;
  1860. struct ggml_tensor * inpL;
  1861. if (tokens) {
  1862. struct ggml_tensor * inp_tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  1863. ggml_allocr_alloc(lctx.alloc, inp_tokens);
  1864. if (!ggml_allocr_is_measure(lctx.alloc)) {
  1865. memcpy(inp_tokens->data, tokens, N*ggml_element_size(inp_tokens));
  1866. }
  1867. ggml_set_name(inp_tokens, "inp_tokens");
  1868. inpL = ggml_get_rows(ctx0, model.tok_embeddings, inp_tokens);
  1869. } else {
  1870. #ifdef GGML_USE_MPI
  1871. GGML_ASSERT(false && "not implemented");
  1872. #endif
  1873. inpL = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N);
  1874. ggml_allocr_alloc(lctx.alloc, inpL);
  1875. if (!ggml_allocr_is_measure(lctx.alloc)) {
  1876. memcpy(inpL->data, embd, N * n_embd * ggml_element_size(inpL));
  1877. }
  1878. }
  1879. const int i_gpu_start = n_layer - n_gpu_layers;
  1880. (void) i_gpu_start;
  1881. // offload functions set the tensor output backend to GPU
  1882. // tensors are GPU-accelerated if any input or the output has been offloaded
  1883. //
  1884. // with the low VRAM option VRAM scratch is disabled in llama_load_model_internal
  1885. // in that case ggml_cuda_assign_buffers has no effect
  1886. offload_func_t offload_func_nr = llama_nop; // nr = non-repeating
  1887. offload_func_t offload_func_kq = llama_nop;
  1888. offload_func_t offload_func_v = llama_nop;
  1889. #ifdef GGML_USE_CUBLAS
  1890. if (n_gpu_layers > n_layer) {
  1891. offload_func_nr = ggml_cuda_assign_buffers_no_alloc;
  1892. }
  1893. if (n_gpu_layers > n_layer + 1) {
  1894. offload_func_v = ggml_cuda_assign_buffers_no_alloc;
  1895. }
  1896. if (n_gpu_layers > n_layer + 2) {
  1897. offload_func_kq = ggml_cuda_assign_buffers_no_alloc;
  1898. }
  1899. #endif // GGML_USE_CUBLAS
  1900. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  1901. ggml_allocr_alloc(lctx.alloc, KQ_scale);
  1902. if (!ggml_allocr_is_measure(lctx.alloc)) {
  1903. ggml_set_f32(KQ_scale, 1.0f/sqrtf(float(n_embd)/n_head));
  1904. }
  1905. ggml_set_name(KQ_scale, "1/sqrt(n_embd_head)");
  1906. for (int il = 0; il < n_layer; ++il) {
  1907. ggml_format_name(inpL, "layer_inp_%d", il);
  1908. offload_func_t offload_func = llama_nop;
  1909. #ifdef GGML_USE_CUBLAS
  1910. if (il >= i_gpu_start) {
  1911. offload_func = ggml_cuda_assign_buffers_no_alloc;
  1912. }
  1913. #endif // GGML_USE_CUBLAS
  1914. struct ggml_tensor * inpSA = inpL;
  1915. // norm
  1916. {
  1917. cur = ggml_rms_norm(ctx0, inpL, norm_rms_eps);
  1918. offload_func(cur);
  1919. ggml_set_name(cur, "rms_norm_0");
  1920. // cur = cur*attn_norm(broadcasted)
  1921. cur = ggml_mul(ctx0, cur, model.layers[il].attn_norm);
  1922. offload_func(cur);
  1923. ggml_set_name(cur, "attention_norm_0");
  1924. }
  1925. // self-attention
  1926. {
  1927. // compute Q and K and RoPE them
  1928. struct ggml_tensor * tmpk = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  1929. offload_func_kq(tmpk);
  1930. ggml_set_name(tmpk, "tmpk");
  1931. struct ggml_tensor * tmpq = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  1932. offload_func_kq(tmpq);
  1933. ggml_set_name(tmpq, "tmpq");
  1934. struct ggml_tensor * Kcur = ggml_rope_custom_inplace(ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, N), n_past, n_embd_head, 0, 0, freq_base, freq_scale);
  1935. offload_func_kq(Kcur);
  1936. ggml_set_name(Kcur, "Kcur");
  1937. struct ggml_tensor * Qcur = ggml_rope_custom_inplace(ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, N), n_past, n_embd_head, 0, 0, freq_base, freq_scale);
  1938. offload_func_kq(Qcur);
  1939. ggml_set_name(Qcur, "Qcur");
  1940. // store key and value to memory
  1941. {
  1942. // compute the transposed [N, n_embd] V matrix
  1943. struct ggml_tensor * tmpv = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  1944. offload_func_v(tmpv);
  1945. ggml_set_name(tmpv, "tmpv");
  1946. struct ggml_tensor * Vcur = ggml_transpose(ctx0, ggml_reshape_2d(ctx0, tmpv, n_embd_gqa, N));
  1947. offload_func_v(Vcur);
  1948. ggml_set_name(Vcur, "Vcur");
  1949. struct ggml_tensor * k = ggml_view_1d(ctx0, kv_self.k, N*n_embd_gqa, (ggml_element_size(kv_self.k)*n_embd_gqa)*(il*n_ctx + n_past));
  1950. offload_func_kq(k);
  1951. ggml_set_name(k, "k");
  1952. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd_gqa,
  1953. ( n_ctx)*ggml_element_size(kv_self.v),
  1954. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd_gqa + n_past*ggml_element_size(kv_self.v));
  1955. offload_func_v(v);
  1956. ggml_set_name(v, "v");
  1957. // important: storing RoPE-ed version of K in the KV cache!
  1958. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
  1959. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
  1960. }
  1961. struct ggml_tensor * Q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  1962. offload_func_kq(Q);
  1963. ggml_set_name(Q, "Q");
  1964. struct ggml_tensor * K =
  1965. ggml_view_3d(ctx0, kv_self.k,
  1966. n_embd_head, n_past + N, n_head_kv,
  1967. ggml_element_size(kv_self.k)*n_embd_gqa,
  1968. ggml_element_size(kv_self.k)*n_embd_head,
  1969. ggml_element_size(kv_self.k)*n_embd_gqa*n_ctx*il);
  1970. offload_func_kq(K);
  1971. ggml_set_name(K, "K");
  1972. // K * Q
  1973. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  1974. offload_func_kq(KQ);
  1975. ggml_set_name(KQ, "KQ");
  1976. // KQ_scaled = KQ / sqrt(n_embd_head)
  1977. // KQ_scaled shape [n_past + N, N, n_head, 1]
  1978. struct ggml_tensor * KQ_scaled = ggml_scale_inplace(ctx0, KQ, KQ_scale);
  1979. offload_func_kq(KQ_scaled);
  1980. ggml_set_name(KQ_scaled, "KQ_scaled");
  1981. // KQ_masked = mask_past(KQ_scaled)
  1982. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf_inplace(ctx0, KQ_scaled, n_past);
  1983. offload_func_kq(KQ_masked);
  1984. ggml_set_name(KQ_masked, "KQ_masked");
  1985. // KQ = soft_max(KQ_masked)
  1986. struct ggml_tensor * KQ_soft_max = ggml_soft_max_inplace(ctx0, KQ_masked);
  1987. offload_func_v(KQ_soft_max);
  1988. ggml_set_name(KQ_soft_max, "KQ_soft_max");
  1989. // split cached V into n_head heads
  1990. struct ggml_tensor * V =
  1991. ggml_view_3d(ctx0, kv_self.v,
  1992. n_past + N, n_embd_head, n_head_kv,
  1993. ggml_element_size(kv_self.v)*n_ctx,
  1994. ggml_element_size(kv_self.v)*n_ctx*n_embd_head,
  1995. ggml_element_size(kv_self.v)*n_ctx*n_embd_gqa*il);
  1996. offload_func_v(V);
  1997. ggml_set_name(V, "V");
  1998. #if 1
  1999. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  2000. offload_func_v(KQV);
  2001. ggml_set_name(KQV, "KQV");
  2002. #else
  2003. // make V contiguous in memory to speed up the matmul, however we waste time on the copy
  2004. // on M1 this is faster for the perplexity computation, but ~5% slower for the single-token generation
  2005. // is there a better way?
  2006. struct ggml_tensor * V_cont = ggml_cpy(ctx0, V, ggml_new_tensor_3d(ctx0, kv_self.v->type, n_past + N, n_embd_head, n_head));
  2007. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V_cont, KQ_soft_max);
  2008. #endif
  2009. // KQV_merged = KQV.permute(0, 2, 1, 3)
  2010. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  2011. offload_func_v(KQV_merged);
  2012. ggml_set_name(KQV_merged, "KQV_merged");
  2013. // cur = KQV_merged.contiguous().view(n_embd, N)
  2014. cur = ggml_cpy(ctx0,
  2015. KQV_merged,
  2016. ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  2017. offload_func_v(cur);
  2018. ggml_set_name(cur, "KQV_merged_contiguous");
  2019. // projection (no bias)
  2020. cur = ggml_mul_mat(ctx0,
  2021. model.layers[il].wo,
  2022. cur);
  2023. offload_func(cur);
  2024. ggml_set_name(cur, "result_wo");
  2025. }
  2026. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  2027. offload_func(inpFF);
  2028. ggml_set_name(inpFF, "inpFF");
  2029. // feed-forward network
  2030. {
  2031. // norm
  2032. {
  2033. cur = ggml_rms_norm(ctx0, inpFF, norm_rms_eps);
  2034. offload_func(cur);
  2035. ggml_set_name(cur, "rms_norm_1");
  2036. // cur = cur*ffn_norm(broadcasted)
  2037. cur = ggml_mul(ctx0, cur, model.layers[il].ffn_norm);
  2038. offload_func(cur);
  2039. ggml_set_name(cur, "ffn_norm");
  2040. }
  2041. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  2042. model.layers[il].w3,
  2043. cur);
  2044. offload_func(tmp);
  2045. ggml_set_name(tmp, "result_w3");
  2046. cur = ggml_mul_mat(ctx0,
  2047. model.layers[il].w1,
  2048. cur);
  2049. offload_func(cur);
  2050. ggml_set_name(cur, "result_w1");
  2051. // SILU activation
  2052. cur = ggml_silu(ctx0, cur);
  2053. offload_func(cur);
  2054. ggml_set_name(cur, "silu");
  2055. cur = ggml_mul(ctx0, cur, tmp);
  2056. offload_func(cur);
  2057. ggml_set_name(cur, "silu_x_result_w3");
  2058. cur = ggml_mul_mat(ctx0,
  2059. model.layers[il].w2,
  2060. cur);
  2061. offload_func(cur);
  2062. ggml_set_name(cur, "result_w2");
  2063. }
  2064. cur = ggml_add(ctx0, cur, inpFF);
  2065. offload_func(cur);
  2066. ggml_set_name(cur, "inpFF_+_result_w2");
  2067. // input for next layer
  2068. inpL = cur;
  2069. }
  2070. cur = inpL;
  2071. // norm
  2072. {
  2073. cur = ggml_rms_norm(ctx0, cur, norm_rms_eps);
  2074. offload_func_nr(cur);
  2075. ggml_set_name(cur, "rms_norm_2");
  2076. // cur = cur*norm(broadcasted)
  2077. cur = ggml_mul(ctx0, cur, model.output_norm);
  2078. // offload_func_nr(cur); // TODO CPU + GPU mirrored backend
  2079. ggml_set_name(cur, "result_norm");
  2080. }
  2081. // lm_head
  2082. cur = ggml_mul_mat(ctx0, model.output, cur);
  2083. ggml_set_name(cur, "result_output");
  2084. ggml_build_forward_expand(gf, cur);
  2085. ggml_free(ctx0);
  2086. return gf;
  2087. }
  2088. static struct ggml_cgraph * llm_build_falcon(
  2089. llama_context & lctx,
  2090. const llama_token * tokens,
  2091. const float * embd,
  2092. int n_tokens,
  2093. int n_past) {
  2094. GGML_ASSERT((!tokens && embd) || (tokens && !embd)); // NOLINT
  2095. const int N = n_tokens;
  2096. const auto & model = lctx.model;
  2097. const auto & hparams = model.hparams;
  2098. const auto & kv_self = lctx.kv_self;
  2099. GGML_ASSERT(!!kv_self.ctx);
  2100. const int64_t n_embd = hparams.n_embd;
  2101. const int64_t n_layer = hparams.n_layer;
  2102. const int64_t n_ctx = hparams.n_ctx;
  2103. const int64_t n_head = hparams.n_head;
  2104. const int64_t n_head_kv = hparams.n_head_kv;
  2105. const int64_t n_embd_head = hparams.n_embd_head();
  2106. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  2107. GGML_ASSERT(n_embd_head == hparams.n_rot);
  2108. const float freq_base = hparams.rope_freq_base;
  2109. const float freq_scale = hparams.rope_freq_scale;
  2110. const float norm_eps = hparams.f_norm_eps;
  2111. const int n_gpu_layers = model.n_gpu_layers;
  2112. auto & buf_compute = lctx.buf_compute;
  2113. struct ggml_init_params params = {
  2114. /*.mem_size =*/ buf_compute.size,
  2115. /*.mem_buffer =*/ buf_compute.data,
  2116. /*.no_alloc =*/ false,
  2117. };
  2118. params.no_alloc = true;
  2119. struct ggml_context * ctx0 = ggml_init(params);
  2120. ggml_cgraph * gf = ggml_new_graph(ctx0);
  2121. struct ggml_tensor * cur;
  2122. struct ggml_tensor * inpL;
  2123. if (tokens) {
  2124. struct ggml_tensor * inp_tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  2125. ggml_allocr_alloc(lctx.alloc, inp_tokens);
  2126. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2127. memcpy(inp_tokens->data, tokens, N*ggml_element_size(inp_tokens));
  2128. }
  2129. ggml_set_name(inp_tokens, "inp_tokens");
  2130. inpL = ggml_get_rows(ctx0, model.tok_embeddings, inp_tokens);
  2131. } else {
  2132. #ifdef GGML_USE_MPI
  2133. GGML_ASSERT(false && "not implemented");
  2134. #endif
  2135. inpL = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N);
  2136. ggml_allocr_alloc(lctx.alloc, inpL);
  2137. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2138. memcpy(inpL->data, embd, N * n_embd * ggml_element_size(inpL));
  2139. }
  2140. }
  2141. const int i_gpu_start = n_layer - n_gpu_layers;
  2142. (void) i_gpu_start;
  2143. // offload functions set the tensor output backend to GPU
  2144. // tensors are GPU-accelerated if any input or the output has been offloaded
  2145. //
  2146. // with the low VRAM option VRAM scratch is disabled in llama_load_model_internal
  2147. // in that case ggml_cuda_assign_buffers has no effect
  2148. offload_func_t offload_func_nr = llama_nop; // nr = non-repeating
  2149. offload_func_t offload_func_kq = llama_nop;
  2150. offload_func_t offload_func_v = llama_nop;
  2151. #ifdef GGML_USE_CUBLAS
  2152. if (n_gpu_layers > n_layer) {
  2153. offload_func_nr = ggml_cuda_assign_buffers_no_alloc;
  2154. }
  2155. if (n_gpu_layers > n_layer + 1) {
  2156. offload_func_v = ggml_cuda_assign_buffers_no_alloc;
  2157. }
  2158. if (n_gpu_layers > n_layer + 2) {
  2159. offload_func_kq = ggml_cuda_assign_buffers_no_alloc;
  2160. }
  2161. #endif // GGML_USE_CUBLAS
  2162. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  2163. ggml_allocr_alloc(lctx.alloc, KQ_scale);
  2164. if (!ggml_allocr_is_measure(lctx.alloc)) {
  2165. ggml_set_f32(KQ_scale, 1.0f/sqrtf(float(n_embd)/n_head));
  2166. }
  2167. ggml_set_name(KQ_scale, "1/sqrt(n_embd_head)");
  2168. for (int il = 0; il < n_layer; ++il) {
  2169. struct ggml_tensor * attn_norm;
  2170. offload_func_t offload_func = llama_nop;
  2171. #ifdef GGML_USE_CUBLAS
  2172. if (il >= i_gpu_start) {
  2173. offload_func = ggml_cuda_assign_buffers_no_alloc;
  2174. }
  2175. #endif // GGML_USE_CUBLAS
  2176. // self-attention
  2177. // TODO: refactor into common function (shared with LLaMA)
  2178. {
  2179. attn_norm = ggml_norm(ctx0, inpL, norm_eps);
  2180. offload_func(attn_norm);
  2181. attn_norm = ggml_add(ctx0,
  2182. ggml_mul(ctx0, attn_norm, model.layers[il].attn_norm),
  2183. model.layers[il].attn_norm_b);
  2184. offload_func(attn_norm->src[0]);
  2185. offload_func(attn_norm);
  2186. if (model.layers[il].attn_norm_2) { // Falcon-40B
  2187. cur = ggml_norm(ctx0, inpL, norm_eps);
  2188. offload_func(cur);
  2189. cur = ggml_add(ctx0,
  2190. ggml_mul(ctx0, cur, model.layers[il].attn_norm_2),
  2191. model.layers[il].attn_norm_2_b);
  2192. offload_func(cur->src[0]);
  2193. offload_func(cur);
  2194. } else { // Falcon 7B
  2195. cur = attn_norm;
  2196. }
  2197. // compute QKV
  2198. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  2199. offload_func_kq(cur);
  2200. // Note that the strides for Kcur, Vcur are set up so that the
  2201. // resulting views are misaligned with the tensor's storage
  2202. // (by applying the K/V offset we shift the tensor's original
  2203. // view to stick out behind the viewed QKV tensor's allocated
  2204. // memory, so to say). This is ok because no actual accesses
  2205. // happen to that out-of-range memory, but it can require some
  2206. // trickery when trying to accurately dump these views for
  2207. // debugging.
  2208. const size_t wsize = ggml_type_size(cur->type);
  2209. // TODO: these 2 ggml_conts are technically not needed, but we add them until CUDA support for
  2210. // non-contiguous views is added for the rope operator
  2211. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_3d(
  2212. ctx0, cur, n_embd_head, n_head, N,
  2213. wsize * n_embd_head,
  2214. wsize * n_embd_head * (n_head + 2 * n_head_kv),
  2215. 0));
  2216. offload_func_kq(tmpq);
  2217. struct ggml_tensor * tmpk = ggml_cont(ctx0, ggml_view_3d(
  2218. ctx0, cur, n_embd_head, n_head_kv, N,
  2219. wsize * n_embd_head,
  2220. wsize * n_embd_head * (n_head + 2 * n_head_kv),
  2221. wsize * n_embd_head * n_head));
  2222. offload_func_kq(tmpk);
  2223. struct ggml_tensor * tmpv = ggml_view_3d(
  2224. ctx0, cur, n_embd_head, n_head_kv, N,
  2225. wsize * n_embd_head,
  2226. wsize * n_embd_head * (n_head + 2 * n_head_kv),
  2227. wsize * n_embd_head * (n_head + n_head_kv));
  2228. offload_func_v(tmpv);
  2229. // using mode = 2 for neox mode
  2230. struct ggml_tensor * Qcur = ggml_rope_custom_inplace(ctx0, tmpq, n_past, n_embd_head, 2, 0, freq_base, freq_scale);
  2231. offload_func_kq(Qcur);
  2232. struct ggml_tensor * Kcur = ggml_rope_custom_inplace(ctx0, tmpk, n_past, n_embd_head, 2, 0, freq_base, freq_scale);
  2233. offload_func_kq(Kcur);
  2234. {
  2235. struct ggml_tensor * Vcur = ggml_transpose(ctx0, ggml_reshape_2d(ctx0, ggml_cont(ctx0, tmpv), n_embd_gqa, N));
  2236. offload_func_v(Vcur);
  2237. offload_func_v(Vcur->src[0]->src[0]);
  2238. ggml_set_name(Vcur, "Vcur");
  2239. struct ggml_tensor * k = ggml_view_1d(ctx0, kv_self.k, N*n_embd_gqa, (ggml_element_size(kv_self.k)*n_embd_gqa)*(il*n_ctx + n_past));
  2240. offload_func_kq(k);
  2241. ggml_set_name(k, "k");
  2242. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd_gqa,
  2243. ( n_ctx)*ggml_element_size(kv_self.v),
  2244. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd_gqa + n_past*ggml_element_size(kv_self.v));
  2245. offload_func_v(v);
  2246. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
  2247. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
  2248. }
  2249. struct ggml_tensor * Q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  2250. offload_func_kq(Q);
  2251. ggml_set_name(Q, "Q");
  2252. struct ggml_tensor * K =
  2253. ggml_view_3d(ctx0, kv_self.k,
  2254. n_embd_head, n_past + N, n_head_kv,
  2255. ggml_element_size(kv_self.k)*n_embd_gqa,
  2256. ggml_element_size(kv_self.k)*n_embd_head,
  2257. ggml_element_size(kv_self.k)*n_embd_gqa*n_ctx*il);
  2258. offload_func_kq(K);
  2259. ggml_set_name(K, "K");
  2260. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  2261. offload_func_kq(KQ);
  2262. ggml_set_name(KQ, "KQ");
  2263. struct ggml_tensor * KQ_scaled = ggml_scale_inplace(ctx0, KQ, KQ_scale);
  2264. offload_func_kq(KQ_scaled);
  2265. ggml_set_name(KQ_scaled, "KQ_scaled");
  2266. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf_inplace(ctx0, KQ_scaled, n_past);
  2267. offload_func_kq(KQ_masked);
  2268. ggml_set_name(KQ_masked, "KQ_masked");
  2269. struct ggml_tensor * KQ_soft_max = ggml_soft_max_inplace(ctx0, KQ_masked);
  2270. offload_func_v(KQ_soft_max);
  2271. ggml_set_name(KQ_soft_max, "KQ_soft_max");
  2272. struct ggml_tensor * V =
  2273. ggml_view_3d(ctx0, kv_self.v,
  2274. n_past + N, n_embd_head, n_head_kv,
  2275. ggml_element_size(kv_self.v)*n_ctx,
  2276. ggml_element_size(kv_self.v)*n_ctx*n_embd_head,
  2277. ggml_element_size(kv_self.v)*n_ctx*n_embd_gqa*il);
  2278. offload_func_v(V);
  2279. ggml_set_name(V, "V");
  2280. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  2281. offload_func_v(KQV);
  2282. ggml_set_name(KQV, "KQV");
  2283. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  2284. offload_func_v(KQV_merged);
  2285. ggml_set_name(KQV_merged, "KQV_merged");
  2286. cur = ggml_cpy(ctx0, KQV_merged, ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  2287. offload_func_v(cur);
  2288. ggml_set_name(cur, "KQV_merged_contiguous");
  2289. cur = ggml_mul_mat(ctx0, model.layers[il].wo, cur);
  2290. offload_func(cur);
  2291. ggml_set_name(cur, "result_wo");
  2292. }
  2293. struct ggml_tensor * attn_out = cur;
  2294. // feed forward
  2295. {
  2296. struct ggml_tensor * inpFF = attn_norm;
  2297. cur = ggml_mul_mat(ctx0, model.layers[il].w3, inpFF);
  2298. offload_func(cur);
  2299. cur = ggml_gelu(ctx0, cur);
  2300. offload_func(cur);
  2301. cur = ggml_mul_mat(ctx0, model.layers[il].w2, cur);
  2302. offload_func(cur);
  2303. }
  2304. cur = ggml_add(ctx0, cur, attn_out);
  2305. offload_func(cur);
  2306. cur = ggml_add(ctx0, cur, inpL);
  2307. offload_func(cur);
  2308. // input for next layer
  2309. inpL = cur;
  2310. }
  2311. cur = inpL;
  2312. // norm
  2313. {
  2314. cur = ggml_norm(ctx0, cur, norm_eps);
  2315. offload_func_nr(cur);
  2316. cur = ggml_add(ctx0,
  2317. ggml_mul(ctx0, cur, model.output_norm),
  2318. model.output_norm_b);
  2319. ggml_set_name(cur, "result_norm");
  2320. }
  2321. cur = ggml_mul_mat(ctx0, model.output, cur);
  2322. ggml_set_name(cur, "result_output");
  2323. ggml_build_forward_expand(gf, cur);
  2324. ggml_free(ctx0);
  2325. return gf;
  2326. }
  2327. static struct ggml_cgraph * llama_build_graph(
  2328. llama_context & lctx,
  2329. const llama_token * tokens,
  2330. const float * embd,
  2331. int n_tokens,
  2332. int n_past) {
  2333. const auto & model = lctx.model;
  2334. struct ggml_cgraph * result = NULL;
  2335. switch (model.arch) {
  2336. case LLM_ARCH_LLAMA:
  2337. {
  2338. result = llm_build_llama(lctx, tokens, embd, n_tokens, n_past);
  2339. } break;
  2340. case LLM_ARCH_FALCON:
  2341. {
  2342. result = llm_build_falcon(lctx, tokens, embd, n_tokens, n_past);
  2343. } break;
  2344. default:
  2345. GGML_ASSERT(false);
  2346. };
  2347. return result;
  2348. }
  2349. // evaluate the transformer
  2350. //
  2351. // - lctx: llama context
  2352. // - tokens: new batch of tokens to process
  2353. // - embd embeddings input
  2354. // - n_tokens number of tokens
  2355. // - n_past: the context size so far
  2356. // - n_threads: number of threads to use
  2357. //
  2358. static bool llama_eval_internal(
  2359. llama_context & lctx,
  2360. const llama_token * tokens,
  2361. const float * embd,
  2362. int n_tokens,
  2363. int n_past,
  2364. int n_threads,
  2365. const char * cgraph_fname) {
  2366. GGML_ASSERT((!tokens && embd) || (tokens && !embd)); // NOLINT
  2367. GGML_ASSERT(n_tokens > 0);
  2368. GGML_ASSERT(n_past >= 0);
  2369. // TODO: keep the values of n_batch and n_ctx
  2370. // GGML_ASSERT(n_tokens <= n_batch);
  2371. // GGML_ASSERT(n_past + n_tokens <= n_ctx);
  2372. const int64_t t_start_us = ggml_time_us();
  2373. #ifdef GGML_USE_MPI
  2374. ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  2375. #endif
  2376. GGML_ASSERT(n_threads > 0);
  2377. const int N = n_tokens;
  2378. const auto & model = lctx.model;
  2379. const auto & hparams = model.hparams;
  2380. const auto & kv_self = lctx.kv_self;
  2381. GGML_ASSERT(!!kv_self.ctx);
  2382. const int64_t n_embd = hparams.n_embd;
  2383. const int64_t n_vocab = hparams.n_vocab;
  2384. ggml_allocr_reset(lctx.alloc);
  2385. ggml_cgraph * gf = llama_build_graph(lctx, tokens, embd, n_tokens, n_past);
  2386. ggml_allocr_alloc_graph(lctx.alloc, gf);
  2387. #ifdef GGML_USE_CUBLAS
  2388. for (int i = 0; i < gf->n_leafs; i++) {
  2389. ggml_tensor * node = gf->leafs[i];
  2390. if (node->backend == GGML_BACKEND_GPU && node->extra == NULL) {
  2391. ggml_cuda_assign_scratch_offset(node, (char*)node->data - (char *) lctx.buf_alloc.data);
  2392. }
  2393. }
  2394. for (int i = 0; i < gf->n_nodes; i++) {
  2395. ggml_tensor * node = gf->nodes[i];
  2396. if (node->backend == GGML_BACKEND_GPU && node->extra == NULL) {
  2397. ggml_cuda_assign_scratch_offset(node, (char*)node->data - (char *) lctx.buf_alloc.data);
  2398. }
  2399. }
  2400. #endif
  2401. // 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);
  2402. // for big prompts, if BLAS is enabled, it is better to use only one thread
  2403. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  2404. n_threads = N >= 32 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas() ? 1 : n_threads;
  2405. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  2406. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 2];
  2407. GGML_ASSERT(strcmp(res->name, "result_output") == 0);
  2408. GGML_ASSERT(strcmp(embeddings->name, "result_norm") == 0);
  2409. #if GGML_USE_MPI
  2410. const int64_t n_layer = hparams.n_layer;
  2411. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  2412. #endif
  2413. #ifdef GGML_USE_METAL
  2414. if (lctx.ctx_metal) {
  2415. ggml_metal_set_n_cb (lctx.ctx_metal, n_threads);
  2416. ggml_metal_graph_compute(lctx.ctx_metal, gf);
  2417. ggml_metal_get_tensor (lctx.ctx_metal, res);
  2418. if (!lctx.embedding.empty()) {
  2419. ggml_metal_get_tensor(lctx.ctx_metal, embeddings);
  2420. }
  2421. } else {
  2422. ggml_graph_compute_helper(lctx.work_buffer, gf, n_threads);
  2423. }
  2424. #else
  2425. ggml_graph_compute_helper(lctx.work_buffer, gf, n_threads);
  2426. #endif
  2427. #if GGML_USE_MPI
  2428. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  2429. #endif
  2430. // update kv token count
  2431. lctx.kv_self.n = n_past + N;
  2432. if (cgraph_fname) {
  2433. ggml_graph_export(gf, cgraph_fname);
  2434. }
  2435. #ifdef GGML_PERF
  2436. // print timing information per ggml operation (for debugging purposes)
  2437. // requires GGML_PERF to be defined
  2438. ggml_graph_print(gf);
  2439. #endif
  2440. // plot the computation graph in dot format (for debugging purposes)
  2441. //if (n_past%100 == 0) {
  2442. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  2443. //}
  2444. // extract logits
  2445. {
  2446. auto & logits_out = lctx.logits;
  2447. if (lctx.logits_all) {
  2448. logits_out.resize(n_vocab * N);
  2449. memcpy(logits_out.data(), (float *) ggml_get_data(res), sizeof(float)*n_vocab*N);
  2450. } else {
  2451. // return result for just the last token
  2452. logits_out.resize(n_vocab);
  2453. memcpy(logits_out.data(), (float *) ggml_get_data(res) + (n_vocab*(N-1)), sizeof(float)*n_vocab);
  2454. }
  2455. }
  2456. // extract embeddings
  2457. if (!lctx.embedding.empty()) {
  2458. auto & embedding_out = lctx.embedding;
  2459. embedding_out.resize(n_embd);
  2460. memcpy(embedding_out.data(), (float *) ggml_get_data(embeddings) + (n_embd*(N - 1)), sizeof(float)*n_embd);
  2461. }
  2462. // measure the performance only for the single-token evals
  2463. if (N == 1) {
  2464. lctx.t_eval_us += ggml_time_us() - t_start_us;
  2465. lctx.n_eval++;
  2466. }
  2467. else if (N > 1) {
  2468. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  2469. lctx.n_p_eval += N;
  2470. }
  2471. return true;
  2472. }
  2473. //
  2474. // tokenizer
  2475. //
  2476. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  2477. return vocab.type;
  2478. }
  2479. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  2480. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  2481. }
  2482. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  2483. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  2484. }
  2485. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  2486. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  2487. }
  2488. static bool llama_is_user_defined_token(const llama_vocab & vocab, llama_token id) {
  2489. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  2490. }
  2491. static bool llama_is_unused_token(const llama_vocab & vocab, llama_token id) {
  2492. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNUSED;
  2493. }
  2494. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  2495. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  2496. }
  2497. static bool llama_is_bos_token(const llama_vocab & vocab, llama_token id) {
  2498. GGML_ASSERT(llama_is_control_token(vocab, id));
  2499. return id == vocab.special_bos_id;
  2500. }
  2501. static bool llama_is_eos_token(const llama_vocab & vocab, llama_token id ) {
  2502. GGML_ASSERT(llama_is_control_token(vocab, id));
  2503. return id == vocab.special_eos_id;
  2504. }
  2505. static bool llama_is_pad_token(const llama_vocab & vocab, llama_token id ) {
  2506. GGML_ASSERT(id < 0 || llama_is_control_token(vocab, id));
  2507. return id == vocab.special_pad_id;
  2508. }
  2509. static uint8_t llama_token_to_byte(const llama_vocab & vocab, llama_token id) {
  2510. GGML_ASSERT(llama_is_byte_token(vocab, id));
  2511. const auto& token_data = vocab.id_to_token.at(id);
  2512. auto buf = token_data.text.substr(3, 2);
  2513. return strtol(buf.c_str(), NULL, 16);
  2514. }
  2515. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  2516. char buf[7];
  2517. int result = snprintf(buf, sizeof(buf), "<0x%02X>", ch);
  2518. GGML_ASSERT(0 <= result && result < 7);
  2519. return vocab.token_to_id.at(buf);
  2520. }
  2521. static void llama_escape_whitespace(std::string & text) {
  2522. replace_all(text, " ", "\xe2\x96\x81");
  2523. }
  2524. static void llama_unescape_whitespace(std::string & word) {
  2525. replace_all(word, "\xe2\x96\x81", " ");
  2526. }
  2527. struct llm_symbol {
  2528. using index = int;
  2529. index prev;
  2530. index next;
  2531. const char * text;
  2532. size_t n;
  2533. };
  2534. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  2535. // SPM tokenizer
  2536. // original implementation:
  2537. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  2538. struct llm_bigram_spm {
  2539. struct comparator {
  2540. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  2541. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  2542. }
  2543. };
  2544. using queue_storage = std::vector<llm_bigram_spm>;
  2545. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  2546. llm_symbol::index left;
  2547. llm_symbol::index right;
  2548. float score;
  2549. size_t size;
  2550. };
  2551. struct llm_tokenizer_spm {
  2552. llm_tokenizer_spm(const llama_vocab & vocab): vocab(vocab) {}
  2553. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  2554. // split string into utf8 chars
  2555. int index = 0;
  2556. size_t offs = 0;
  2557. while (offs < text.size()) {
  2558. llm_symbol sym;
  2559. size_t len = utf8_len(text[offs]);
  2560. GGML_ASSERT(offs + len <= text.size());
  2561. sym.text = text.c_str() + offs;
  2562. sym.n = len;
  2563. offs += len;
  2564. sym.prev = index - 1;
  2565. sym.next = offs == text.size() ? -1 : index + 1;
  2566. index++;
  2567. symbols.emplace_back(sym);
  2568. }
  2569. // seed the work queue with all possible 2-character tokens.
  2570. for (size_t i = 1; i < symbols.size(); ++i) {
  2571. try_add_bigram(i - 1, i);
  2572. }
  2573. // keep substituting the highest frequency pairs for as long as we can.
  2574. while (!work_queue.empty()) {
  2575. auto bigram = work_queue.top();
  2576. work_queue.pop();
  2577. auto & left_sym = symbols[bigram.left];
  2578. auto & right_sym = symbols[bigram.right];
  2579. // if one of the symbols already got merged, skip it.
  2580. if (left_sym.n == 0 || right_sym.n == 0 ||
  2581. left_sym.n + right_sym.n != bigram.size) {
  2582. continue;
  2583. }
  2584. // merge the right sym into the left one
  2585. left_sym.n += right_sym.n;
  2586. right_sym.n = 0;
  2587. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  2588. // remove the right sym from the chain
  2589. left_sym.next = right_sym.next;
  2590. if (right_sym.next >= 0) {
  2591. symbols[right_sym.next].prev = bigram.left;
  2592. }
  2593. // find more substitutions
  2594. try_add_bigram(left_sym.prev, bigram.left);
  2595. try_add_bigram(bigram.left, left_sym.next);
  2596. }
  2597. for (int i = 0; i != -1; i = symbols[i].next) {
  2598. auto & symbol = symbols[i];
  2599. resegment(symbol, output);
  2600. }
  2601. }
  2602. private:
  2603. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  2604. auto text = std::string(symbol.text, symbol.n);
  2605. auto token = vocab.token_to_id.find(text);
  2606. // Do we need to support is_unused?
  2607. if (token != vocab.token_to_id.end()) {
  2608. output.push_back((*token).second);
  2609. return;
  2610. }
  2611. const auto p = rev_merge.find(text);
  2612. if (p == rev_merge.end()) {
  2613. // output any symbols that did not form tokens as bytes.
  2614. for (int j = 0; j < (int)symbol.n; ++j) {
  2615. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  2616. output.push_back(token_id);
  2617. }
  2618. return;
  2619. }
  2620. resegment(symbols[p->second.first], output);
  2621. resegment(symbols[p->second.second], output);
  2622. }
  2623. void try_add_bigram(int left, int right) {
  2624. if (left == -1 || right == -1) {
  2625. return;
  2626. }
  2627. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  2628. auto token = vocab.token_to_id.find(text);
  2629. if (token == vocab.token_to_id.end()) {
  2630. return;
  2631. }
  2632. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  2633. return;
  2634. }
  2635. const auto & tok_data = vocab.id_to_token[(*token).second];
  2636. llm_bigram_spm bigram;
  2637. bigram.left = left;
  2638. bigram.right = right;
  2639. bigram.score = tok_data.score;
  2640. bigram.size = text.size();
  2641. work_queue.push(bigram);
  2642. // Do we need to support is_unused?
  2643. rev_merge[text] = std::make_pair(left, right);
  2644. }
  2645. const llama_vocab & vocab;
  2646. std::vector<llm_symbol> symbols;
  2647. llm_bigram_spm::queue work_queue;
  2648. std::map<std::string, std::pair<int, int>> rev_merge;
  2649. };
  2650. // BPE tokenizer
  2651. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  2652. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  2653. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  2654. struct llm_bigram_bpe {
  2655. struct comparator {
  2656. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  2657. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  2658. }
  2659. };
  2660. using queue_storage = std::vector<llm_bigram_bpe>;
  2661. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  2662. llm_symbol::index left;
  2663. llm_symbol::index right;
  2664. std::string text;
  2665. int rank;
  2666. size_t size;
  2667. };
  2668. struct llm_tokenizer_bpe {
  2669. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  2670. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  2671. int final_prev_index = -1;
  2672. auto word_collection = bpe_gpt2_preprocess(text);
  2673. symbols_final.clear();
  2674. for (auto & word : word_collection) {
  2675. work_queue = llm_bigram_bpe::queue();
  2676. symbols.clear();
  2677. int index = 0;
  2678. size_t offset = 0;
  2679. while (offset < word.size()) {
  2680. llm_symbol sym;
  2681. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  2682. sym.text = word.c_str() + offset;
  2683. sym.n = 1;
  2684. sym.n = char_len;
  2685. offset += sym.n;
  2686. sym.prev = index - 1;
  2687. sym.next = offset == word.size() ? -1 : index + 1;
  2688. index++;
  2689. symbols.emplace_back(sym);
  2690. }
  2691. for (size_t i = 1; i < symbols.size(); ++i) {
  2692. add_new_bigram(i - 1, i);
  2693. }
  2694. // build token(s)
  2695. while (!work_queue.empty()) {
  2696. auto bigram = work_queue.top();
  2697. work_queue.pop();
  2698. auto & left_symbol = symbols[bigram.left];
  2699. auto & right_symbol = symbols[bigram.right];
  2700. if (left_symbol.n == 0 || right_symbol.n == 0) {
  2701. continue;
  2702. }
  2703. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  2704. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  2705. if (left_token + right_token != bigram.text) {
  2706. continue; // Skip this bigram if it's outdated
  2707. }
  2708. // merge the right sym into the left one
  2709. left_symbol.n += right_symbol.n;
  2710. right_symbol.n = 0;
  2711. // remove the right sym from the chain
  2712. left_symbol.next = right_symbol.next;
  2713. if (right_symbol.next >= 0) {
  2714. symbols[right_symbol.next].prev = bigram.left;
  2715. }
  2716. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  2717. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  2718. }
  2719. // add the fnished tokens to the final list keeping correct order for next and prev
  2720. for (auto & sym : symbols) {
  2721. if (sym.n > 0) {
  2722. sym.prev = final_prev_index;
  2723. sym.next = -1;
  2724. if (final_prev_index != -1) {
  2725. symbols_final[final_prev_index].next = symbols_final.size();
  2726. }
  2727. symbols_final.emplace_back(sym);
  2728. final_prev_index = symbols_final.size() - 1;
  2729. }
  2730. }
  2731. }
  2732. symbols = symbols_final;
  2733. if (!symbols.empty()) {
  2734. for (int i = 0; i != -1; i = symbols[i].next) {
  2735. auto & symbol = symbols[i];
  2736. if (symbol.n == 0) {
  2737. continue;
  2738. }
  2739. const std::string str = std::string(symbol.text, symbol.n);
  2740. const auto token = vocab.token_to_id.find(str);
  2741. if (token == vocab.token_to_id.end()) {
  2742. for (auto j = str.begin(); j != str.end(); ++j) {
  2743. std::string byte_str(1, *j);
  2744. auto token_multibyte = vocab.token_to_id.find(byte_str);
  2745. if (token_multibyte == vocab.token_to_id.end()) {
  2746. fprintf(stderr,"ERROR: byte not found in vocab: '%s'\n", byte_str.c_str());
  2747. }
  2748. output.push_back((*token_multibyte).second);
  2749. }
  2750. } else {
  2751. output.push_back((*token).second);
  2752. }
  2753. }
  2754. }
  2755. }
  2756. private:
  2757. void add_new_bigram(int left, int right) {
  2758. if (left == -1 || right == -1) {
  2759. return;
  2760. }
  2761. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  2762. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  2763. int rank_found = -1;
  2764. rank_found = vocab.find_bpe_rank(left_token, right_token);
  2765. if (rank_found < 0) {
  2766. return;
  2767. }
  2768. llm_bigram_bpe bigram;
  2769. bigram.left = left;
  2770. bigram.right = right;
  2771. bigram.text = left_token + right_token;
  2772. bigram.size = left_token.size() + right_token.size();
  2773. bigram.rank = rank_found;
  2774. work_queue.push(bigram);
  2775. }
  2776. // probably not 100% correct
  2777. static std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  2778. std::vector<std::string> words;
  2779. // ref: https://github.com/openai/gpt-2/blob/a74da5d99abaaba920de8131d64da2862a8f213b/src/encoder.py#L53
  2780. const std::string pattern = R"('s|'t|'re|'ve|'m|'ll|'d| ?[[:alpha:]]+| ?[[:digit:]]+| ?[^\s[:alpha:][:digit:]]+|\s+(?!\S)|\s+)";
  2781. const std::regex re(pattern);
  2782. auto words_begin = std::sregex_iterator(text.begin(), text.end(), re);
  2783. auto words_end = std::sregex_iterator();
  2784. auto n_words = std::distance(words_begin, words_end);
  2785. words.reserve(n_words);
  2786. for (auto it = words_begin; it != words_end; ++it) {
  2787. words.push_back(it->str());
  2788. }
  2789. return words;
  2790. }
  2791. const llama_vocab & vocab;
  2792. std::vector<llm_symbol> symbols;
  2793. std::vector<llm_symbol> symbols_final;
  2794. llm_bigram_bpe::queue work_queue;
  2795. };
  2796. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos) {
  2797. std::vector<llama_vocab::id> output;
  2798. // OG tokenizer behavior:
  2799. //
  2800. // tokenizer.encode('', add_bos=True) returns [1]
  2801. // tokenizer.encode('', add_bos=False) returns []
  2802. if (bos && vocab.special_bos_id != -1) {
  2803. output.push_back(vocab.special_bos_id);
  2804. }
  2805. if (raw_text.empty()) {
  2806. return output;
  2807. }
  2808. switch (vocab.type) {
  2809. case LLAMA_VOCAB_TYPE_SPM:
  2810. {
  2811. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  2812. raw_text = " " + raw_text;
  2813. llm_tokenizer_spm tokenizer(vocab);
  2814. llama_escape_whitespace(raw_text);
  2815. tokenizer.tokenize(raw_text, output);
  2816. } break;
  2817. case LLAMA_VOCAB_TYPE_BPE:
  2818. {
  2819. llm_tokenizer_bpe tokenizer(vocab);
  2820. tokenizer.tokenize(raw_text, output);
  2821. } break;
  2822. };
  2823. return output;
  2824. }
  2825. //
  2826. // grammar - internal
  2827. //
  2828. struct llama_partial_utf8 {
  2829. uint32_t value; // bit value so far (unshifted)
  2830. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  2831. };
  2832. struct llama_grammar {
  2833. const std::vector<std::vector<llama_grammar_element>> rules;
  2834. std::vector<std::vector<const llama_grammar_element *>> stacks;
  2835. // buffer for partially generated UTF-8 sequence from accepted tokens
  2836. llama_partial_utf8 partial_utf8;
  2837. };
  2838. struct llama_grammar_candidate {
  2839. size_t index;
  2840. const uint32_t * code_points;
  2841. llama_partial_utf8 partial_utf8;
  2842. };
  2843. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  2844. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  2845. std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  2846. const char * src,
  2847. llama_partial_utf8 partial_start) {
  2848. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  2849. const char * pos = src;
  2850. std::vector<uint32_t> code_points;
  2851. uint32_t value = partial_start.value;
  2852. int n_remain = partial_start.n_remain;
  2853. // continue previous decode, if applicable
  2854. while (*pos != 0 && n_remain > 0) {
  2855. uint8_t next_byte = static_cast<uint8_t>(*pos);
  2856. if ((next_byte >> 6) != 2) {
  2857. // invalid sequence, abort
  2858. code_points.push_back(0);
  2859. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  2860. }
  2861. value = (value << 6) + (next_byte & 0x3F);
  2862. ++pos;
  2863. --n_remain;
  2864. }
  2865. if (partial_start.n_remain > 0 && n_remain == 0) {
  2866. code_points.push_back(value);
  2867. }
  2868. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  2869. while (*pos != 0) {
  2870. uint8_t first_byte = static_cast<uint8_t>(*pos);
  2871. uint8_t highbits = first_byte >> 4;
  2872. n_remain = lookup[highbits] - 1;
  2873. if (n_remain < 0) {
  2874. // invalid sequence, abort
  2875. code_points.clear();
  2876. code_points.push_back(0);
  2877. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  2878. }
  2879. uint8_t mask = (1 << (7 - n_remain)) - 1;
  2880. value = first_byte & mask;
  2881. ++pos;
  2882. while (*pos != 0 && n_remain > 0) {
  2883. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  2884. ++pos;
  2885. --n_remain;
  2886. }
  2887. if (n_remain == 0) {
  2888. code_points.push_back(value);
  2889. }
  2890. }
  2891. code_points.push_back(0);
  2892. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  2893. }
  2894. // returns true iff pos points to the end of one of the definitions of a rule
  2895. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  2896. switch (pos->type) {
  2897. case LLAMA_GRETYPE_END: return true; // NOLINT
  2898. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  2899. default: return false;
  2900. }
  2901. }
  2902. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  2903. // asserts that pos is pointing to a char range element
  2904. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  2905. const llama_grammar_element * pos,
  2906. const uint32_t chr) {
  2907. bool found = false;
  2908. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  2909. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  2910. do {
  2911. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  2912. // inclusive range, e.g. [a-z]
  2913. found = found || (pos->value <= chr && chr <= pos[1].value);
  2914. pos += 2;
  2915. } else {
  2916. // exact char match, e.g. [a] or "a"
  2917. found = found || pos->value == chr;
  2918. pos += 1;
  2919. }
  2920. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  2921. return std::make_pair(found == is_positive_char, pos);
  2922. }
  2923. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  2924. // range at pos (regular or inverse range)
  2925. // asserts that pos is pointing to a char range element
  2926. static bool llama_grammar_match_partial_char(
  2927. const llama_grammar_element * pos,
  2928. const llama_partial_utf8 partial_utf8) {
  2929. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  2930. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  2931. uint32_t partial_value = partial_utf8.value;
  2932. int n_remain = partial_utf8.n_remain;
  2933. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  2934. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  2935. return false;
  2936. }
  2937. // range of possible code points this partial UTF-8 sequence could complete to
  2938. uint32_t low = partial_value << (n_remain * 6);
  2939. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  2940. if (low == 0) {
  2941. if (n_remain == 2) {
  2942. low = 1 << 11;
  2943. } else if (n_remain == 3) {
  2944. low = 1 << 16;
  2945. }
  2946. }
  2947. do {
  2948. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  2949. // inclusive range, e.g. [a-z]
  2950. if (pos->value <= high && low <= pos[1].value) {
  2951. return is_positive_char;
  2952. }
  2953. pos += 2;
  2954. } else {
  2955. // exact char match, e.g. [a] or "a"
  2956. if (low <= pos->value && pos->value <= high) {
  2957. return is_positive_char;
  2958. }
  2959. pos += 1;
  2960. }
  2961. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  2962. return !is_positive_char;
  2963. }
  2964. // transforms a grammar pushdown stack into N possible stacks, all ending
  2965. // at a character range (terminal element)
  2966. static void llama_grammar_advance_stack(
  2967. const std::vector<std::vector<llama_grammar_element>> & rules,
  2968. const std::vector<const llama_grammar_element *> & stack,
  2969. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  2970. if (stack.empty()) {
  2971. new_stacks.emplace_back(stack);
  2972. return;
  2973. }
  2974. const llama_grammar_element * pos = stack.back();
  2975. switch (pos->type) {
  2976. case LLAMA_GRETYPE_RULE_REF: {
  2977. const size_t rule_id = static_cast<size_t>(pos->value);
  2978. const llama_grammar_element * subpos = rules[rule_id].data();
  2979. do {
  2980. // init new stack without the top (pos)
  2981. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  2982. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  2983. // if this rule ref is followed by another element, add that to stack
  2984. new_stack.push_back(pos + 1);
  2985. }
  2986. if (!llama_grammar_is_end_of_sequence(subpos)) {
  2987. // if alternate is nonempty, add to stack
  2988. new_stack.push_back(subpos);
  2989. }
  2990. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  2991. while (!llama_grammar_is_end_of_sequence(subpos)) {
  2992. // scan to end of alternate def
  2993. subpos++;
  2994. }
  2995. if (subpos->type == LLAMA_GRETYPE_ALT) {
  2996. // there's another alternate def of this rule to process
  2997. subpos++;
  2998. } else {
  2999. break;
  3000. }
  3001. } while (true);
  3002. break;
  3003. }
  3004. case LLAMA_GRETYPE_CHAR:
  3005. case LLAMA_GRETYPE_CHAR_NOT:
  3006. new_stacks.emplace_back(stack);
  3007. break;
  3008. default:
  3009. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  3010. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  3011. // those
  3012. GGML_ASSERT(false);
  3013. }
  3014. }
  3015. // takes a set of possible pushdown stacks on a grammar, which are required to
  3016. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  3017. // produces the N possible stacks if the given char is accepted at those
  3018. // positions
  3019. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  3020. const std::vector<std::vector<llama_grammar_element>> & rules,
  3021. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  3022. const uint32_t chr) {
  3023. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  3024. for (const auto & stack : stacks) {
  3025. if (stack.empty()) {
  3026. continue;
  3027. }
  3028. auto match = llama_grammar_match_char(stack.back(), chr);
  3029. if (match.first) {
  3030. const llama_grammar_element * pos = match.second;
  3031. // update top of stack to next element, if any
  3032. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  3033. if (!llama_grammar_is_end_of_sequence(pos)) {
  3034. new_stack.push_back(pos);
  3035. }
  3036. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  3037. }
  3038. }
  3039. return new_stacks;
  3040. }
  3041. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  3042. const std::vector<std::vector<llama_grammar_element>> & rules,
  3043. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  3044. const std::vector<llama_grammar_candidate> & candidates);
  3045. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  3046. const std::vector<std::vector<llama_grammar_element>> & rules,
  3047. const std::vector<const llama_grammar_element *> & stack,
  3048. const std::vector<llama_grammar_candidate> & candidates) {
  3049. std::vector<llama_grammar_candidate> rejects;
  3050. if (stack.empty()) {
  3051. for (auto tok : candidates) {
  3052. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  3053. rejects.push_back(tok);
  3054. }
  3055. }
  3056. return rejects;
  3057. }
  3058. const llama_grammar_element * stack_pos = stack.back();
  3059. std::vector<llama_grammar_candidate> next_candidates;
  3060. for (auto tok : candidates) {
  3061. if (*tok.code_points == 0) {
  3062. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  3063. // that cannot satisfy this position in grammar
  3064. if (tok.partial_utf8.n_remain != 0 &&
  3065. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  3066. rejects.push_back(tok);
  3067. }
  3068. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  3069. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  3070. } else {
  3071. rejects.push_back(tok);
  3072. }
  3073. }
  3074. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  3075. // update top of stack to next element, if any
  3076. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  3077. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  3078. stack_after.push_back(stack_pos_after);
  3079. }
  3080. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  3081. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  3082. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  3083. for (auto tok : next_rejects) {
  3084. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  3085. }
  3086. return rejects;
  3087. }
  3088. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  3089. const std::vector<std::vector<llama_grammar_element>> & rules,
  3090. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  3091. const std::vector<llama_grammar_candidate> & candidates) {
  3092. GGML_ASSERT(!stacks.empty()); // REVIEW
  3093. if (candidates.empty()) {
  3094. return std::vector<llama_grammar_candidate>();
  3095. }
  3096. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  3097. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  3098. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  3099. }
  3100. return rejects;
  3101. }
  3102. //
  3103. // grammar - external
  3104. //
  3105. struct llama_grammar * llama_grammar_init(
  3106. const llama_grammar_element ** rules,
  3107. size_t n_rules,
  3108. size_t start_rule_index) {
  3109. const llama_grammar_element * pos;
  3110. // copy rule definitions into vectors
  3111. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  3112. for (size_t i = 0; i < n_rules; i++) {
  3113. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  3114. vec_rules[i].push_back(*pos);
  3115. }
  3116. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  3117. }
  3118. // loop over alternates of start rule to build initial stacks
  3119. std::vector<std::vector<const llama_grammar_element *>> stacks;
  3120. pos = rules[start_rule_index];
  3121. do {
  3122. std::vector<const llama_grammar_element *> stack;
  3123. if (!llama_grammar_is_end_of_sequence(pos)) {
  3124. // if alternate is nonempty, add to stack
  3125. stack.push_back(pos);
  3126. }
  3127. llama_grammar_advance_stack(vec_rules, stack, stacks);
  3128. while (!llama_grammar_is_end_of_sequence(pos)) {
  3129. // scan to end of alternate def
  3130. pos++;
  3131. }
  3132. if (pos->type == LLAMA_GRETYPE_ALT) {
  3133. // there's another alternate def of this rule to process
  3134. pos++;
  3135. } else {
  3136. break;
  3137. }
  3138. } while (true);
  3139. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  3140. }
  3141. void llama_grammar_free(struct llama_grammar * grammar) {
  3142. delete grammar;
  3143. }
  3144. //
  3145. // sampling
  3146. //
  3147. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  3148. GGML_ASSERT(candidates->size > 0);
  3149. const int64_t t_start_sample_us = ggml_time_us();
  3150. // Sort the logits in descending order
  3151. if (!candidates->sorted) {
  3152. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  3153. return a.logit > b.logit;
  3154. });
  3155. candidates->sorted = true;
  3156. }
  3157. float max_l = candidates->data[0].logit;
  3158. float cum_sum = 0.0f;
  3159. for (size_t i = 0; i < candidates->size; ++i) {
  3160. float p = expf(candidates->data[i].logit - max_l);
  3161. candidates->data[i].p = p;
  3162. cum_sum += p;
  3163. }
  3164. for (size_t i = 0; i < candidates->size; ++i) {
  3165. candidates->data[i].p /= cum_sum;
  3166. }
  3167. if (ctx) {
  3168. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3169. }
  3170. }
  3171. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int k, size_t min_keep) {
  3172. const int64_t t_start_sample_us = ggml_time_us();
  3173. k = std::max(k, (int) min_keep);
  3174. k = std::min(k, (int) candidates->size);
  3175. // Sort scores in descending order
  3176. if (!candidates->sorted) {
  3177. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  3178. return a.logit > b.logit;
  3179. };
  3180. if (k == (int) candidates->size) {
  3181. std::sort(candidates->data, candidates->data + candidates->size, comp);
  3182. } else {
  3183. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  3184. }
  3185. candidates->sorted = true;
  3186. }
  3187. candidates->size = k;
  3188. if (ctx) {
  3189. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3190. }
  3191. }
  3192. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  3193. if (p >= 1.0f) {
  3194. return;
  3195. }
  3196. llama_sample_softmax(ctx, candidates);
  3197. const int64_t t_start_sample_us = ggml_time_us();
  3198. // Compute the cumulative probabilities
  3199. float cum_sum = 0.0f;
  3200. size_t last_idx = candidates->size;
  3201. for (size_t i = 0; i < candidates->size; ++i) {
  3202. cum_sum += candidates->data[i].p;
  3203. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  3204. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  3205. if (cum_sum >= p && i + 1 >= min_keep) {
  3206. last_idx = i + 1;
  3207. break;
  3208. }
  3209. }
  3210. // Resize the output vector to keep only the top-p tokens
  3211. candidates->size = last_idx;
  3212. if (ctx) {
  3213. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3214. }
  3215. }
  3216. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  3217. if (z >= 1.0f || candidates->size <= 2) {
  3218. return;
  3219. }
  3220. llama_sample_softmax(nullptr, candidates);
  3221. const int64_t t_start_sample_us = ggml_time_us();
  3222. // Compute the first and second derivatives
  3223. std::vector<float> first_derivatives(candidates->size - 1);
  3224. std::vector<float> second_derivatives(candidates->size - 2);
  3225. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  3226. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  3227. }
  3228. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  3229. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  3230. }
  3231. // Calculate absolute value of second derivatives
  3232. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  3233. second_derivatives[i] = std::abs(second_derivatives[i]);
  3234. }
  3235. // Normalize the second derivatives
  3236. {
  3237. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  3238. if (second_derivatives_sum > 1e-6f) {
  3239. for (float & value : second_derivatives) {
  3240. value /= second_derivatives_sum;
  3241. }
  3242. } else {
  3243. for (float & value : second_derivatives) {
  3244. value = 1.0f / second_derivatives.size();
  3245. }
  3246. }
  3247. }
  3248. float cum_sum = 0.0f;
  3249. size_t last_idx = candidates->size;
  3250. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  3251. cum_sum += second_derivatives[i];
  3252. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  3253. if (cum_sum > z && i >= min_keep) {
  3254. last_idx = i;
  3255. break;
  3256. }
  3257. }
  3258. // Resize the output vector to keep only the tokens above the tail location
  3259. candidates->size = last_idx;
  3260. if (ctx) {
  3261. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3262. }
  3263. }
  3264. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  3265. // Reference implementation:
  3266. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  3267. if (p >= 1.0f) {
  3268. return;
  3269. }
  3270. // Compute the softmax of logits and calculate entropy
  3271. llama_sample_softmax(nullptr, candidates);
  3272. const int64_t t_start_sample_us = ggml_time_us();
  3273. float entropy = 0.0f;
  3274. for (size_t i = 0; i < candidates->size; ++i) {
  3275. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  3276. }
  3277. // Compute the absolute difference between negative log probability and entropy for each candidate
  3278. std::vector<float> shifted_scores;
  3279. for (size_t i = 0; i < candidates->size; ++i) {
  3280. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  3281. shifted_scores.push_back(shifted_score);
  3282. }
  3283. // Sort tokens based on the shifted_scores and their corresponding indices
  3284. std::vector<size_t> indices(candidates->size);
  3285. std::iota(indices.begin(), indices.end(), 0);
  3286. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  3287. return shifted_scores[a] < shifted_scores[b];
  3288. });
  3289. // Compute the cumulative probabilities
  3290. float cum_sum = 0.0f;
  3291. size_t last_idx = indices.size();
  3292. for (size_t i = 0; i < indices.size(); ++i) {
  3293. size_t idx = indices[i];
  3294. cum_sum += candidates->data[idx].p;
  3295. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  3296. if (cum_sum > p && i >= min_keep - 1) {
  3297. last_idx = i + 1;
  3298. break;
  3299. }
  3300. }
  3301. // Resize the output vector to keep only the locally typical tokens
  3302. std::vector<llama_token_data> new_candidates;
  3303. for (size_t i = 0; i < last_idx; ++i) {
  3304. size_t idx = indices[i];
  3305. new_candidates.push_back(candidates->data[idx]);
  3306. }
  3307. // Replace the data in candidates with the new_candidates data
  3308. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  3309. candidates->size = new_candidates.size();
  3310. if (ctx) {
  3311. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3312. }
  3313. }
  3314. void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  3315. const int64_t t_start_sample_us = ggml_time_us();
  3316. for (size_t i = 0; i < candidates_p->size; ++i) {
  3317. candidates_p->data[i].logit /= temp;
  3318. }
  3319. if (ctx) {
  3320. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3321. }
  3322. }
  3323. void llama_sample_repetition_penalty(struct llama_context * ctx, llama_token_data_array * candidates, const llama_token * last_tokens, size_t last_tokens_size, float penalty) {
  3324. if (last_tokens_size == 0 || penalty == 1.0f) {
  3325. return;
  3326. }
  3327. const int64_t t_start_sample_us = ggml_time_us();
  3328. for (size_t i = 0; i < candidates->size; ++i) {
  3329. const auto * token_iter = std::find(last_tokens, last_tokens + last_tokens_size, candidates->data[i].id);
  3330. if (token_iter == last_tokens + last_tokens_size) {
  3331. continue;
  3332. }
  3333. // 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.
  3334. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  3335. if (candidates->data[i].logit <= 0) {
  3336. candidates->data[i].logit *= penalty;
  3337. } else {
  3338. candidates->data[i].logit /= penalty;
  3339. }
  3340. }
  3341. candidates->sorted = false;
  3342. if (ctx) {
  3343. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3344. }
  3345. }
  3346. void llama_sample_frequency_and_presence_penalties(struct llama_context * ctx, llama_token_data_array * candidates, const llama_token * last_tokens_p, size_t last_tokens_size, float alpha_frequency, float alpha_presence) {
  3347. if (last_tokens_size == 0 || (alpha_frequency == 0.0f && alpha_presence == 0.0f)) {
  3348. return;
  3349. }
  3350. const int64_t t_start_sample_us = ggml_time_us();
  3351. // Create a frequency map to count occurrences of each token in last_tokens
  3352. std::unordered_map<llama_token, int> token_count;
  3353. for (size_t i = 0; i < last_tokens_size; ++i) {
  3354. token_count[last_tokens_p[i]]++;
  3355. }
  3356. // Apply frequency and presence penalties to the candidates
  3357. for (size_t i = 0; i < candidates->size; ++i) {
  3358. auto token_iter = token_count.find(candidates->data[i].id);
  3359. if (token_iter == token_count.end()) {
  3360. continue;
  3361. }
  3362. int count = token_iter->second;
  3363. candidates->data[i].logit -= float(count) * alpha_frequency + float(count > 0) * alpha_presence;
  3364. }
  3365. candidates->sorted = false;
  3366. if (ctx) {
  3367. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3368. }
  3369. }
  3370. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  3371. GGML_ASSERT(ctx);
  3372. const int64_t t_start_sample_us = ggml_time_us();
  3373. bool allow_eos = false;
  3374. for (const auto & stack : grammar->stacks) {
  3375. if (stack.empty()) {
  3376. allow_eos = true;
  3377. break;
  3378. }
  3379. }
  3380. const llama_token eos = llama_token_eos(ctx);
  3381. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  3382. std::vector<llama_grammar_candidate> candidates_grammar;
  3383. for (size_t i = 0; i < candidates->size; ++i) {
  3384. const llama_token id = candidates->data[i].id;
  3385. const std::string piece = llama_token_to_str(ctx, id);
  3386. if (id == eos) {
  3387. if (!allow_eos) {
  3388. candidates->data[i].logit = -INFINITY;
  3389. }
  3390. } else if (piece.empty() || piece[0] == 0) {
  3391. candidates->data[i].logit = -INFINITY;
  3392. } else {
  3393. candidates_decoded.push_back(decode_utf8(piece.c_str(), grammar->partial_utf8));
  3394. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  3395. }
  3396. }
  3397. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  3398. for (const auto & reject : rejects) {
  3399. candidates->data[reject.index].logit = -INFINITY;
  3400. }
  3401. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3402. }
  3403. static void llama_log_softmax(float * array, size_t size) {
  3404. float max_l = *std::max_element(array, array + size);
  3405. float sum = 0.f;
  3406. for (size_t i = 0; i < size; ++i) {
  3407. float p = expf(array[i] - max_l);
  3408. sum += p;
  3409. array[i] = p;
  3410. }
  3411. for (size_t i = 0; i < size; ++i) {
  3412. array[i] = logf(array[i] / sum);
  3413. }
  3414. }
  3415. void llama_sample_classifier_free_guidance(
  3416. struct llama_context * ctx,
  3417. llama_token_data_array * candidates,
  3418. struct llama_context * guidance_ctx,
  3419. float scale) {
  3420. int64_t t_start_sample_us = ggml_time_us();
  3421. GGML_ASSERT(ctx);
  3422. auto n_vocab = llama_n_vocab(ctx);
  3423. GGML_ASSERT(n_vocab == (int)candidates->size);
  3424. GGML_ASSERT(!candidates->sorted);
  3425. std::vector<float> logits_base;
  3426. logits_base.reserve(candidates->size);
  3427. for (size_t i = 0; i < candidates->size; ++i) {
  3428. logits_base.push_back(candidates->data[i].logit);
  3429. }
  3430. llama_log_softmax(logits_base.data(), candidates->size);
  3431. float* logits_guidance = llama_get_logits(guidance_ctx);
  3432. llama_log_softmax(logits_guidance, n_vocab);
  3433. for (int i = 0; i < n_vocab; ++i) {
  3434. float logit_guidance = logits_guidance[i];
  3435. float logit_base = logits_base[i];
  3436. candidates->data[i].logit = scale * (logit_base - logit_guidance) + logit_guidance;
  3437. }
  3438. if (ctx) {
  3439. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3440. }
  3441. }
  3442. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int m, float * mu) {
  3443. GGML_ASSERT(ctx);
  3444. auto N = float(llama_n_vocab(ctx));
  3445. int64_t t_start_sample_us;
  3446. t_start_sample_us = ggml_time_us();
  3447. llama_sample_softmax(nullptr, candidates);
  3448. // Estimate s_hat using the most probable m tokens
  3449. float s_hat = 0.0;
  3450. float sum_ti_bi = 0.0;
  3451. float sum_ti_sq = 0.0;
  3452. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  3453. float t_i = logf(float(i + 2) / float(i + 1));
  3454. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  3455. sum_ti_bi += t_i * b_i;
  3456. sum_ti_sq += t_i * t_i;
  3457. }
  3458. s_hat = sum_ti_bi / sum_ti_sq;
  3459. // Compute k from the estimated s_hat and target surprise value
  3460. float epsilon_hat = s_hat - 1;
  3461. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  3462. // Sample the next word X using top-k sampling
  3463. llama_sample_top_k(nullptr, candidates, int(k), 1);
  3464. if (ctx) {
  3465. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3466. }
  3467. llama_token X = llama_sample_token(ctx, candidates);
  3468. t_start_sample_us = ggml_time_us();
  3469. // Compute error as the difference between observed surprise and target surprise value
  3470. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  3471. return candidate.id == X;
  3472. }));
  3473. float observed_surprise = -log2f(candidates->data[X_idx].p);
  3474. float e = observed_surprise - tau;
  3475. // Update mu using the learning rate and error
  3476. *mu = *mu - eta * e;
  3477. if (ctx) {
  3478. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3479. }
  3480. return X;
  3481. }
  3482. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  3483. int64_t t_start_sample_us;
  3484. t_start_sample_us = ggml_time_us();
  3485. llama_sample_softmax(ctx, candidates);
  3486. // Truncate the words with surprise values greater than mu
  3487. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  3488. return -log2f(candidate.p) > *mu;
  3489. }));
  3490. if (candidates->size == 0) {
  3491. candidates->size = 1;
  3492. }
  3493. if (ctx) {
  3494. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3495. }
  3496. // Normalize the probabilities of the remaining words
  3497. llama_sample_softmax(ctx, candidates);
  3498. // Sample the next word X from the remaining words
  3499. llama_token X = llama_sample_token(ctx, candidates);
  3500. t_start_sample_us = ggml_time_us();
  3501. // Compute error as the difference between observed surprise and target surprise value
  3502. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  3503. return candidate.id == X;
  3504. }));
  3505. float observed_surprise = -log2f(candidates->data[X_idx].p);
  3506. float e = observed_surprise - tau;
  3507. // Update mu using the learning rate and error
  3508. *mu = *mu - eta * e;
  3509. if (ctx) {
  3510. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3511. }
  3512. return X;
  3513. }
  3514. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  3515. const int64_t t_start_sample_us = ggml_time_us();
  3516. // Find max element
  3517. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  3518. return a.logit < b.logit;
  3519. });
  3520. llama_token result = max_iter->id;
  3521. if (ctx) {
  3522. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3523. ctx->n_sample++;
  3524. }
  3525. return result;
  3526. }
  3527. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  3528. GGML_ASSERT(ctx);
  3529. const int64_t t_start_sample_us = ggml_time_us();
  3530. llama_sample_softmax(nullptr, candidates);
  3531. std::vector<float> probs;
  3532. probs.reserve(candidates->size);
  3533. for (size_t i = 0; i < candidates->size; ++i) {
  3534. probs.push_back(candidates->data[i].p);
  3535. }
  3536. std::discrete_distribution<> dist(probs.begin(), probs.end());
  3537. auto & rng = ctx->rng;
  3538. int idx = dist(rng);
  3539. llama_token result = candidates->data[idx].id;
  3540. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3541. ctx->n_sample++;
  3542. return result;
  3543. }
  3544. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  3545. const int64_t t_start_sample_us = ggml_time_us();
  3546. if (token == llama_token_eos(ctx)) {
  3547. for (const auto & stack : grammar->stacks) {
  3548. if (stack.empty()) {
  3549. return;
  3550. }
  3551. }
  3552. GGML_ASSERT(false);
  3553. }
  3554. const std::string piece = llama_token_to_str(ctx, token);
  3555. // Note terminating 0 in decoded string
  3556. const auto decoded = decode_utf8(piece.c_str(), grammar->partial_utf8);
  3557. const auto & code_points = decoded.first;
  3558. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  3559. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  3560. }
  3561. grammar->partial_utf8 = decoded.second;
  3562. GGML_ASSERT(!grammar->stacks.empty());
  3563. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3564. }
  3565. //
  3566. // Beam search
  3567. //
  3568. struct llama_beam {
  3569. std::vector<llama_token> tokens;
  3570. float p; // Cumulative beam probability (renormalized relative to all beams)
  3571. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  3572. // Sort beams by probability. In case of ties, prefer beams at eob.
  3573. bool operator<(const llama_beam & rhs) const {
  3574. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  3575. }
  3576. // Shift off first n tokens and discard them.
  3577. void shift_tokens(const size_t n) {
  3578. if (n) {
  3579. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  3580. tokens.resize(tokens.size() - n);
  3581. }
  3582. }
  3583. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  3584. };
  3585. // A struct for calculating logit-related info.
  3586. struct llama_logit_info {
  3587. const float * const logits;
  3588. const int n_vocab;
  3589. const float max_l;
  3590. const float normalizer;
  3591. struct sum_exp {
  3592. float max_l;
  3593. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  3594. };
  3595. llama_logit_info(llama_context * ctx)
  3596. : logits(llama_get_logits(ctx))
  3597. , n_vocab(llama_n_vocab(ctx))
  3598. , max_l(*std::max_element(logits, logits + n_vocab))
  3599. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  3600. { }
  3601. llama_token_data get_token_data(const llama_token token_id) const {
  3602. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  3603. return {token_id, logits[token_id], p};
  3604. }
  3605. // Return top k token_data by logit.
  3606. std::vector<llama_token_data> top_k(size_t k) {
  3607. std::vector<llama_token_data> min_heap; // min-heap by logit
  3608. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  3609. min_heap.reserve(k_min);
  3610. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  3611. min_heap.push_back(get_token_data(token_id));
  3612. }
  3613. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  3614. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  3615. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  3616. if (min_heap.front().logit < logits[token_id]) {
  3617. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  3618. min_heap.back().id = token_id;
  3619. min_heap.back().logit = logits[token_id];
  3620. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  3621. }
  3622. }
  3623. return min_heap;
  3624. }
  3625. float probability_from_logit(float logit) const {
  3626. return normalizer * std::exp(logit - max_l);
  3627. }
  3628. };
  3629. struct llama_beam_search_data {
  3630. llama_context * ctx;
  3631. size_t n_beams;
  3632. int n_past;
  3633. int n_predict;
  3634. int n_threads;
  3635. std::vector<llama_beam> beams;
  3636. std::vector<llama_beam> next_beams;
  3637. // Re-calculated on each loop iteration
  3638. size_t common_prefix_length;
  3639. // Used to communicate to/from callback on beams state.
  3640. std::vector<llama_beam_view> beam_views;
  3641. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict, int n_threads)
  3642. : ctx(ctx)
  3643. , n_beams(n_beams)
  3644. , n_past(n_past)
  3645. , n_predict(n_predict)
  3646. , n_threads(n_threads)
  3647. , beam_views(n_beams) {
  3648. beams.reserve(n_beams);
  3649. next_beams.reserve(n_beams);
  3650. }
  3651. // Collapse beams to a single beam given by index.
  3652. void collapse_beams(const size_t beam_idx) {
  3653. if (0u < beam_idx) {
  3654. std::swap(beams[0], beams[beam_idx]);
  3655. }
  3656. beams.resize(1);
  3657. }
  3658. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  3659. // The repetative patterns below reflect the 2 stages of heaps:
  3660. // * Gather elements until the vector is full, then call std::make_heap() on it.
  3661. // * If the heap is full and a new element is found that should be included, pop the
  3662. // least element to the back(), replace it with the new, then push it into the heap.
  3663. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  3664. // Min-heaps use a greater-than comparator.
  3665. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  3666. if (beam.eob) {
  3667. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  3668. if (next_beams.size() < n_beams) {
  3669. next_beams.push_back(std::move(beam));
  3670. if (next_beams.size() == n_beams) {
  3671. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  3672. }
  3673. } else if (next_beams.front().p < beam.p) {
  3674. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  3675. next_beams.back() = std::move(beam);
  3676. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  3677. }
  3678. } else {
  3679. // beam is not at end-of-sentence, so branch with next top_k tokens.
  3680. if (!beam.tokens.empty()) {
  3681. llama_eval(ctx, beam.tokens.data(), beam.tokens.size(), n_past, n_threads);
  3682. }
  3683. llama_logit_info logit_info(ctx);
  3684. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  3685. size_t i=0;
  3686. if (next_beams.size() < n_beams) {
  3687. for (; next_beams.size() < n_beams ; ++i) {
  3688. llama_beam next_beam = beam;
  3689. next_beam.tokens.push_back(next_tokens[i].id);
  3690. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  3691. next_beams.push_back(std::move(next_beam));
  3692. }
  3693. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  3694. } else {
  3695. for (; next_beams.front().p == 0.0f ; ++i) {
  3696. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  3697. next_beams.back() = beam;
  3698. next_beams.back().tokens.push_back(next_tokens[i].id);
  3699. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  3700. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  3701. }
  3702. }
  3703. for (; i < n_beams ; ++i) {
  3704. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  3705. if (next_beams.front().p < next_p) {
  3706. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  3707. next_beams.back() = beam;
  3708. next_beams.back().tokens.push_back(next_tokens[i].id);
  3709. next_beams.back().p = next_p;
  3710. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  3711. }
  3712. }
  3713. }
  3714. }
  3715. // Find common_prefix_length based on beams.
  3716. // Requires beams is not empty.
  3717. size_t find_common_prefix_length() {
  3718. size_t common_prefix_length = beams[0].tokens.size();
  3719. for (size_t i = 1 ; i < beams.size() ; ++i) {
  3720. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  3721. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  3722. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  3723. common_prefix_length = j;
  3724. break;
  3725. }
  3726. }
  3727. }
  3728. return common_prefix_length;
  3729. }
  3730. // Construct beams_state to send back to caller via the callback function.
  3731. // Side effect: set common_prefix_length = find_common_prefix_length();
  3732. llama_beams_state get_beams_state(const bool last_call) {
  3733. for (size_t i = 0 ; i < beams.size() ; ++i) {
  3734. beam_views[i] = beams[i].view();
  3735. }
  3736. common_prefix_length = find_common_prefix_length();
  3737. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  3738. }
  3739. // Loop:
  3740. // * while i < n_predict, AND
  3741. // * any of the beams have not yet reached end-of-beam (eob), AND
  3742. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  3743. // (since all other beam probabilities can only decrease)
  3744. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  3745. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  3746. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  3747. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  3748. !beams[top_beam_index()].eob ; ++i) {
  3749. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  3750. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  3751. if (common_prefix_length) {
  3752. llama_eval(ctx, beams[0].tokens.data(), common_prefix_length, n_past, n_threads);
  3753. n_past += common_prefix_length;
  3754. }
  3755. // Zero-out next_beam probabilities to place them last in following min-heap.
  3756. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  3757. for (llama_beam & beam : beams) {
  3758. beam.shift_tokens(common_prefix_length);
  3759. fill_next_beams_by_top_probabilities(beam);
  3760. }
  3761. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  3762. beams.swap(next_beams);
  3763. renormalize_beam_probabilities(beams);
  3764. }
  3765. collapse_beams(top_beam_index());
  3766. callback(callback_data, get_beams_state(true));
  3767. }
  3768. // As beams grow, the cumulative probabilities decrease.
  3769. // Renormalize them to avoid floating point underflow.
  3770. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  3771. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  3772. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  3773. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  3774. }
  3775. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  3776. size_t top_beam_index() {
  3777. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  3778. }
  3779. // Copy (p,eob) for each beam which may have been changed by the callback.
  3780. void update_beams_from_beam_views() {
  3781. for (size_t i = 0 ; i < beams.size() ; ++i) {
  3782. beams[i].p = beam_views[i].p;
  3783. beams[i].eob = beam_views[i].eob;
  3784. }
  3785. }
  3786. };
  3787. void llama_beam_search(llama_context * ctx,
  3788. llama_beam_search_callback_fn_t callback, void * callback_data,
  3789. size_t n_beams, int n_past, int n_predict, int n_threads) {
  3790. assert(ctx);
  3791. const int64_t t_start_sample_us = ggml_time_us();
  3792. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict, n_threads);
  3793. beam_search_data.loop(callback, callback_data);
  3794. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  3795. ctx->n_sample++;
  3796. }
  3797. //
  3798. // quantization
  3799. //
  3800. static void llama_convert_tensor_internal(struct ggml_tensor * tensor, std::vector<float> & output, const size_t nelements, const int nthread) {
  3801. if (output.size() < nelements) {
  3802. output.resize(nelements);
  3803. }
  3804. float * f32_output = (float *) output.data();
  3805. ggml_type_traits_t qtype;
  3806. if (ggml_is_quantized(tensor->type)) {
  3807. qtype = ggml_internal_get_type_traits(tensor->type);
  3808. if (qtype.to_float == NULL) {
  3809. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  3810. }
  3811. } else if (tensor->type != GGML_TYPE_F16) {
  3812. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  3813. }
  3814. if (nthread < 2) {
  3815. if (tensor->type == GGML_TYPE_F16) {
  3816. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  3817. } else if (ggml_is_quantized(tensor->type)) {
  3818. qtype.to_float(tensor->data, f32_output, nelements);
  3819. } else {
  3820. GGML_ASSERT(false); // unreachable
  3821. }
  3822. return;
  3823. }
  3824. auto block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  3825. auto block_size_bytes = ggml_type_size(tensor->type);
  3826. GGML_ASSERT(nelements % block_size == 0);
  3827. auto nblocks = nelements / block_size;
  3828. auto blocks_per_thread = nblocks / nthread;
  3829. auto spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  3830. std::vector<std::thread> workers;
  3831. for (auto tnum = 0, in_buff_offs = 0, out_buff_offs = 0; tnum < nthread; tnum++) {
  3832. auto thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  3833. auto thr_elems = thr_blocks * block_size; // number of elements for this thread
  3834. auto thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  3835. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  3836. if (typ == GGML_TYPE_F16) {
  3837. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  3838. } else {
  3839. qtype.to_float(inbuf, outbuf, nels);
  3840. }
  3841. };
  3842. workers.push_back(std::thread(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems));
  3843. in_buff_offs += thr_block_bytes;
  3844. out_buff_offs += thr_elems;
  3845. }
  3846. for (auto & worker : workers) {
  3847. worker.join();
  3848. }
  3849. }
  3850. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  3851. ggml_type quantized_type;
  3852. llama_ftype ftype = params->ftype;
  3853. switch (params->ftype) {
  3854. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  3855. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  3856. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  3857. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  3858. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  3859. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  3860. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  3861. #ifdef GGML_USE_K_QUANTS
  3862. // K-quants
  3863. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  3864. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  3865. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  3866. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  3867. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  3868. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  3869. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  3870. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  3871. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  3872. #endif
  3873. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  3874. }
  3875. int nthread = params->nthread;
  3876. if (nthread <= 0) {
  3877. nthread = std::thread::hardware_concurrency();
  3878. }
  3879. std::unique_ptr<llama_model_loader> ml(new llama_model_loader(fname_inp, /*use_mmap*/ false));
  3880. llama_model model;
  3881. llm_load_arch(*ml, model);
  3882. llm_load_hparams(*ml, model, 0, 0, 0);
  3883. if (params->only_copy) {
  3884. ftype = model.ftype;
  3885. }
  3886. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  3887. struct gguf_context * ctx_out = gguf_init_empty();
  3888. // copy the KV pairs from the input file
  3889. gguf_set_kv (ctx_out, ml->ctx_gguf);
  3890. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  3891. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  3892. #ifdef GGML_USE_K_QUANTS
  3893. int n_attention_wv = 0;
  3894. int n_feed_forward_w2 = 0;
  3895. for (int i = 0; i < ml->n_tensors; ++i) {
  3896. struct ggml_tensor * meta = ml->get_tensor_meta(i);
  3897. const std::string name = ggml_get_name(meta);
  3898. // TODO: avoid hardcoded tensor names - use the TN_* constants
  3899. if (name.find("attn_v.weight") != std::string::npos) {
  3900. ++n_attention_wv;
  3901. }
  3902. else if (name.find("ffn_down.weight") != std::string::npos) {
  3903. ++n_feed_forward_w2;
  3904. }
  3905. }
  3906. if (n_attention_wv != n_feed_forward_w2 || (uint32_t)n_attention_wv != model.hparams.n_layer) {
  3907. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_feed_forward_w2 = %d, hparams.n_layer = %d\n",
  3908. __func__, n_attention_wv, n_feed_forward_w2, model.hparams.n_layer);
  3909. }
  3910. int i_attention_wv = 0;
  3911. int i_feed_forward_w2 = 0;
  3912. #endif
  3913. size_t total_size_org = 0;
  3914. size_t total_size_new = 0;
  3915. std::vector<int64_t> hist_all(1 << 4, 0);
  3916. std::vector<std::thread> workers;
  3917. std::mutex mutex;
  3918. auto use_more_bits = [] (int i_layer, int num_layers) -> bool {
  3919. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  3920. };
  3921. int idx = 0;
  3922. std::vector<uint8_t> read_data;
  3923. std::vector<uint8_t> work;
  3924. // populate the original tensors so we get an initial meta data
  3925. for (int i = 0; i < ml->n_tensors; ++i) {
  3926. struct ggml_tensor * meta = ml->get_tensor_meta(i);
  3927. gguf_add_tensor(ctx_out, meta);
  3928. }
  3929. std::ofstream fout(fname_out, std::ios::binary);
  3930. const size_t meta_size = gguf_get_meta_size(ctx_out);
  3931. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  3932. // placeholder for the meta data
  3933. ::zeros(fout, meta_size);
  3934. for (int i = 0; i < ml->n_tensors; ++i) {
  3935. struct ggml_tensor * tensor = ml->get_tensor_meta(i);
  3936. const std::string name = ggml_get_name(tensor);
  3937. read_data.resize(ggml_nbytes(tensor));
  3938. tensor->data = read_data.data();
  3939. ml->load_data_for(tensor);
  3940. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  3941. ++idx, ml->n_tensors,
  3942. ggml_get_name(tensor),
  3943. llama_format_tensor_shape(tensor).c_str(),
  3944. ggml_type_name(tensor->type));
  3945. // This used to be a regex, but <regex> has an extreme cost to compile times.
  3946. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  3947. // quantize only 2D tensors
  3948. quantize &= (tensor->n_dims == 2);
  3949. quantize &= params->quantize_output_tensor || name != "output.weight";
  3950. quantize &= !params->only_copy;
  3951. enum ggml_type new_type;
  3952. void * new_data;
  3953. size_t new_size;
  3954. if (quantize) {
  3955. new_type = quantized_type;
  3956. #ifdef GGML_USE_K_QUANTS
  3957. // TODO: avoid hardcoded tensor names - use the TN_* constants
  3958. const auto tn = LLM_TN(ml->get_arch());
  3959. if (name == tn(LLM_TENSOR_OUTPUT, "weight")) {
  3960. int nx = tensor->ne[0];
  3961. if (model.arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  3962. new_type = GGML_TYPE_Q8_0;
  3963. }
  3964. else if (new_type != GGML_TYPE_Q8_0) {
  3965. new_type = GGML_TYPE_Q6_K;
  3966. }
  3967. } else if (name.find("attn_v.weight") != std::string::npos) {
  3968. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  3969. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  3970. new_type = i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  3971. }
  3972. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  3973. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  3974. use_more_bits(i_attention_wv, n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  3975. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  3976. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  3977. (i_attention_wv < n_attention_wv/8 || i_attention_wv >= 7*n_attention_wv/8)) new_type = GGML_TYPE_Q6_K;
  3978. if (model.type == MODEL_70B) {
  3979. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  3980. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  3981. // nearly negligible increase in model size by quantizing this tensor with more bits:
  3982. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  3983. }
  3984. ++i_attention_wv;
  3985. } else if (name.find("ffn_down.weight") != std::string::npos) {
  3986. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  3987. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  3988. new_type = i_feed_forward_w2 < 2 ? GGML_TYPE_Q5_K
  3989. : model.arch != LLM_ARCH_FALCON || use_more_bits(i_feed_forward_w2, n_feed_forward_w2) ? GGML_TYPE_Q4_K
  3990. : GGML_TYPE_Q3_K;
  3991. }
  3992. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  3993. new_type = model.arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  3994. }
  3995. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  3996. if (model.arch == LLM_ARCH_FALCON) {
  3997. new_type = i_feed_forward_w2 < 2 ? GGML_TYPE_Q6_K :
  3998. use_more_bits(i_feed_forward_w2, n_feed_forward_w2) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  3999. } else {
  4000. if (use_more_bits(i_feed_forward_w2, n_feed_forward_w2)) new_type = GGML_TYPE_Q6_K;
  4001. }
  4002. }
  4003. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_feed_forward_w2, n_feed_forward_w2)) new_type = GGML_TYPE_Q6_K;
  4004. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && model.arch != LLM_ARCH_FALCON && i_feed_forward_w2 < 4) {
  4005. new_type = GGML_TYPE_Q5_K;
  4006. }
  4007. ++i_feed_forward_w2;
  4008. } else if (name.find("attn_output.weight") != std::string::npos) {
  4009. if (model.arch != LLM_ARCH_FALCON) {
  4010. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  4011. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) new_type = GGML_TYPE_Q4_K;
  4012. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  4013. } else {
  4014. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  4015. }
  4016. }
  4017. else if (name.find("attn_qkv.weight") != std::string::npos) {
  4018. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  4019. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  4020. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  4021. }
  4022. else if (name.find("ffn_gate.weight") != std::string::npos || name.find("ffn_up.weight") != std::string::npos) {
  4023. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  4024. }
  4025. // This can be used to reduce the size of the Q5_K_S model.
  4026. // The associated PPL increase is fully in line with the size reduction
  4027. //else {
  4028. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  4029. //}
  4030. bool convert_incompatible_tensor = false;
  4031. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  4032. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K) {
  4033. int nx = tensor->ne[0];
  4034. int ny = tensor->ne[1];
  4035. if (nx % QK_K != 0) {
  4036. LLAMA_LOG_WARN("\n\n%s : tensor cols %d x %d are not divisible by %d, required for k-quants\n", __func__, nx, ny, QK_K);
  4037. convert_incompatible_tensor = true;
  4038. }
  4039. }
  4040. if (convert_incompatible_tensor) {
  4041. if (name == tn(LLM_TENSOR_OUTPUT, "weight")) {
  4042. new_type = GGML_TYPE_F16; //fall back to F16 instead of just failing.
  4043. LLAMA_LOG_WARN("F16 will be used for this tensor instead.\n");
  4044. } else if (name == tn(LLM_TENSOR_TOKEN_EMBD, "weight")) {
  4045. new_type = GGML_TYPE_Q4_0; //fall back to Q4_0 instead of just failing.
  4046. LLAMA_LOG_WARN("Q4_0 will be used for this tensor instead.\n");
  4047. } else {
  4048. throw std::runtime_error("Unsupported tensor size encountered\n");
  4049. }
  4050. }
  4051. #endif
  4052. // If we've decided to quantize to the same type the tensor is already
  4053. // in then there's nothing to do.
  4054. quantize = tensor->type != new_type;
  4055. }
  4056. if (!quantize) {
  4057. new_type = tensor->type;
  4058. new_data = tensor->data;
  4059. new_size = ggml_nbytes(tensor);
  4060. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  4061. } else {
  4062. const size_t nelements = ggml_nelements(tensor);
  4063. float * f32_data;
  4064. std::vector<float> f32_conv_buf;
  4065. if (tensor->type == GGML_TYPE_F32) {
  4066. f32_data = (float *) tensor->data;
  4067. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  4068. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  4069. } else {
  4070. llama_convert_tensor_internal(tensor, f32_conv_buf, nelements, nthread);
  4071. f32_data = (float *) f32_conv_buf.data();
  4072. }
  4073. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  4074. fflush(stdout);
  4075. work.resize(nelements * 4); // upper bound on size
  4076. new_data = work.data();
  4077. std::vector<int64_t> hist_cur(1 << 4, 0);
  4078. static const int chunk_size = 32 * 512;
  4079. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  4080. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  4081. if (nthread_use < 2) {
  4082. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nelements, hist_cur.data());
  4083. } else {
  4084. size_t counter = 0;
  4085. new_size = 0;
  4086. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, nelements]() {
  4087. std::vector<int64_t> local_hist;
  4088. size_t local_size = 0;
  4089. while (true) {
  4090. std::unique_lock<std::mutex> lock(mutex);
  4091. size_t first = counter; counter += chunk_size;
  4092. if (first >= nelements) {
  4093. if (!local_hist.empty()) {
  4094. for (int j=0; j<int(local_hist.size()); ++j) {
  4095. hist_cur[j] += local_hist[j];
  4096. }
  4097. new_size += local_size;
  4098. }
  4099. break;
  4100. }
  4101. lock.unlock();
  4102. size_t last = std::min(nelements, first + chunk_size);
  4103. if (local_hist.empty()) {
  4104. local_hist.resize(hist_cur.size(), 0);
  4105. }
  4106. local_size += ggml_quantize_chunk(new_type, f32_data, new_data, first, last - first, local_hist.data());
  4107. }
  4108. };
  4109. if ((int) workers.size() < nthread_use - 1) {
  4110. workers.resize(nthread_use - 1);
  4111. }
  4112. for (int it = 0; it < nthread_use - 1; ++it) {
  4113. workers[it] = std::thread(compute);
  4114. }
  4115. compute();
  4116. for (int it = 0; it < nthread_use - 1; ++it) {
  4117. workers[it].join();
  4118. }
  4119. }
  4120. LLAMA_LOG_INFO("size = %8.2f MB -> %8.2f MB | hist: ", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  4121. int64_t tot_count = 0;
  4122. for (size_t i = 0; i < hist_cur.size(); i++) {
  4123. hist_all[i] += hist_cur[i];
  4124. tot_count += hist_cur[i];
  4125. }
  4126. if (tot_count > 0) {
  4127. for (size_t i = 0; i < hist_cur.size(); i++) {
  4128. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  4129. }
  4130. }
  4131. LLAMA_LOG_INFO("\n");
  4132. }
  4133. total_size_org += ggml_nbytes(tensor);
  4134. total_size_new += new_size;
  4135. // update the gguf meta data as we go
  4136. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  4137. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  4138. // write tensor data + padding
  4139. fout.write((const char *) new_data, new_size);
  4140. zeros(fout, GGML_PAD(new_size, align) - new_size);
  4141. }
  4142. // go back to beginning of file and write the updated meta data
  4143. {
  4144. fout.seekp(0);
  4145. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  4146. gguf_get_meta_data(ctx_out, data.data());
  4147. fout.write((const char *) data.data(), data.size());
  4148. }
  4149. fout.close();
  4150. gguf_free(ctx_out);
  4151. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  4152. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  4153. // print histogram for all tensors
  4154. {
  4155. int64_t sum_all = 0;
  4156. for (size_t i = 0; i < hist_all.size(); i++) {
  4157. sum_all += hist_all[i];
  4158. }
  4159. if (sum_all > 0) {
  4160. LLAMA_LOG_INFO("%s: hist: ", __func__);
  4161. for (size_t i = 0; i < hist_all.size(); i++) {
  4162. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  4163. }
  4164. LLAMA_LOG_INFO("\n");
  4165. }
  4166. }
  4167. }
  4168. // TODO: after the GGUF PR, this likely won't work and needs to be updated
  4169. int llama_apply_lora_from_file_internal(const struct llama_model & model, const char * path_lora, const char * path_base_model, int n_threads) {
  4170. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  4171. const int64_t t_start_lora_us = ggml_time_us();
  4172. auto fin = std::ifstream(path_lora, std::ios::binary);
  4173. if (!fin) {
  4174. LLAMA_LOG_ERROR("%s: failed to open '%s'\n", __func__, path_lora);
  4175. return 1;
  4176. }
  4177. // verify magic and version
  4178. {
  4179. uint32_t magic;
  4180. fin.read((char *) &magic, sizeof(magic));
  4181. uint32_t format_version;
  4182. fin.read((char *) &format_version, sizeof(format_version));
  4183. if (format_version != 1) {
  4184. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  4185. return 1;
  4186. }
  4187. }
  4188. int32_t lora_r;
  4189. int32_t lora_alpha;
  4190. fin.read((char *) &lora_r, sizeof(lora_r));
  4191. fin.read((char *) &lora_alpha, sizeof(lora_alpha));
  4192. float scaling = (float)lora_alpha / (float)lora_r;
  4193. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  4194. // create a temporary ggml context to store the lora tensors
  4195. // todo: calculate size from biggest possible tensor
  4196. std::vector<uint8_t> lora_buf(1024ull * 1024ull * 1024ull);
  4197. struct ggml_init_params params;
  4198. params.mem_size = lora_buf.size();
  4199. params.mem_buffer = lora_buf.data();
  4200. params.no_alloc = false;
  4201. ggml_context * lora_ctx = ggml_init(params);
  4202. std::unordered_map<std::string, struct ggml_tensor *> lora_tensors;
  4203. // create a name -> tensor map of the model to accelerate lookups
  4204. std::unordered_map<std::string, struct ggml_tensor*> model_tensors;
  4205. for (const auto & kv : model.tensors_by_name) {
  4206. model_tensors.insert(kv);
  4207. }
  4208. // load base model
  4209. std::unique_ptr<llama_model_loader> ml;
  4210. ggml_context * base_ctx = NULL;
  4211. std::vector<uint8_t> base_buf;
  4212. if (path_base_model) {
  4213. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  4214. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true));
  4215. size_t ctx_size;
  4216. size_t mmapped_size;
  4217. ml->calc_sizes(ctx_size, mmapped_size);
  4218. base_buf.resize(ctx_size);
  4219. ggml_init_params base_params;
  4220. base_params.mem_size = base_buf.size();
  4221. base_params.mem_buffer = base_buf.data();
  4222. base_params.no_alloc = ml->use_mmap;
  4223. base_ctx = ggml_init(base_params);
  4224. // maybe this should in llama_model_loader
  4225. if (ml->use_mmap) {
  4226. ml->mapping.reset(new llama_mmap(&ml->file, /* prefetch */ 0, ggml_is_numa()));
  4227. }
  4228. }
  4229. // read tensors and apply
  4230. bool warned = false;
  4231. int n_tensors = 0;
  4232. std::vector<uint8_t> work_buffer;
  4233. while (true) {
  4234. int32_t n_dims;
  4235. int32_t length;
  4236. int32_t ftype;
  4237. fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  4238. fin.read(reinterpret_cast<char *>(&length), sizeof(length));
  4239. fin.read(reinterpret_cast<char *>(&ftype), sizeof(ftype));
  4240. if (fin.eof()) {
  4241. break;
  4242. }
  4243. int32_t ne[2] = { 1, 1 };
  4244. for (int i = 0; i < n_dims; ++i) {
  4245. fin.read(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  4246. }
  4247. std::string name;
  4248. {
  4249. char buf[1024];
  4250. fin.read(buf, length);
  4251. name = std::string(buf, length);
  4252. }
  4253. // check for lora suffix and get the type of tensor
  4254. const std::string lora_suffix = ".lora";
  4255. size_t pos = name.rfind(lora_suffix);
  4256. if (pos == std::string::npos) {
  4257. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  4258. return 1;
  4259. }
  4260. std::string lora_type = name.substr(pos + lora_suffix.length());
  4261. std::string base_name = name;
  4262. base_name.erase(pos);
  4263. // LLAMA_LOG_INFO("%s: %s => %s (lora type %s) \n", __func__, name.c_str(),base_name.c_str(), lora_type.c_str());
  4264. if (model_tensors.find(base_name) == model_tensors.end()) {
  4265. LLAMA_LOG_ERROR("%s: unknown tensor '%s' in lora adapter\n", __func__, name.data());
  4266. return 1;
  4267. }
  4268. // create ggml tensor
  4269. ggml_type wtype;
  4270. switch (ftype) {
  4271. case 0: wtype = GGML_TYPE_F32; break;
  4272. case 1: wtype = GGML_TYPE_F16; break;
  4273. default:
  4274. {
  4275. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  4276. __func__, ftype);
  4277. return false;
  4278. }
  4279. }
  4280. ggml_tensor * lora_tensor;
  4281. if (n_dims == 2) {
  4282. lora_tensor = ggml_new_tensor_2d(lora_ctx, wtype, ne[0], ne[1]);
  4283. }
  4284. else {
  4285. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  4286. return 1;
  4287. }
  4288. ggml_set_name(lora_tensor, "lora_tensor");
  4289. // load tensor data
  4290. size_t offset = fin.tellg();
  4291. size_t tensor_data_size = ggml_nbytes(lora_tensor);
  4292. offset = (offset + 31) & -32;
  4293. fin.seekg(offset);
  4294. fin.read((char*)lora_tensor->data, tensor_data_size);
  4295. lora_tensors[name] = lora_tensor;
  4296. // check if we have both A and B tensors and apply
  4297. if (lora_tensors.find(base_name + ".loraA") != lora_tensors.end() &&
  4298. lora_tensors.find(base_name + ".loraB") != lora_tensors.end()) {
  4299. ggml_tensor * dest_t = model_tensors[base_name];
  4300. offload_func_t offload_func = llama_nop;
  4301. offload_func_t offload_func_force_inplace = llama_nop;
  4302. #ifdef GGML_USE_CUBLAS
  4303. if (dest_t->backend == GGML_BACKEND_GPU || dest_t->backend == GGML_BACKEND_GPU_SPLIT) {
  4304. if (dest_t->type != GGML_TYPE_F16) {
  4305. throw std::runtime_error(format(
  4306. "%s: error: the simultaneous use of LoRAs and GPU acceleration is only supported for f16 models", __func__));
  4307. }
  4308. offload_func = ggml_cuda_assign_buffers;
  4309. offload_func_force_inplace = ggml_cuda_assign_buffers_force_inplace;
  4310. }
  4311. #endif // GGML_USE_CUBLAS
  4312. ggml_tensor * base_t;
  4313. if (ml) {
  4314. struct gguf_context * ctx_gguf = ml->ctx_gguf;
  4315. // load from base model
  4316. if (gguf_find_tensor(ctx_gguf, base_name.c_str()) < 0) {
  4317. // TODO: throw
  4318. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  4319. return 1;
  4320. }
  4321. // TODO: not tested!! maybe not working!
  4322. base_t = ml->create_tensor(base_ctx, base_name, { (uint32_t)dest_t->ne[0], (uint32_t)dest_t->ne[1] }, GGML_BACKEND_CPU);
  4323. ml->load_data_for(base_t);
  4324. } else {
  4325. base_t = dest_t;
  4326. }
  4327. if (ggml_is_quantized(base_t->type)) {
  4328. if (!warned) {
  4329. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  4330. "use a f16 or f32 base model with --lora-base\n", __func__);
  4331. warned = true;
  4332. }
  4333. }
  4334. ggml_tensor * loraA = lora_tensors[base_name + ".loraA"];
  4335. GGML_ASSERT(loraA->type == GGML_TYPE_F32);
  4336. ggml_set_name(loraA, "loraA");
  4337. ggml_tensor * loraB = lora_tensors[base_name + ".loraB"];
  4338. GGML_ASSERT(loraB->type == GGML_TYPE_F32);
  4339. ggml_set_name(loraB, "loraB");
  4340. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  4341. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  4342. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  4343. return 1;
  4344. }
  4345. // w = w + BA*s
  4346. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  4347. offload_func(BA);
  4348. ggml_set_name(BA, "BA");
  4349. if (scaling != 1.0f) {
  4350. ggml_tensor * scale_tensor = ggml_new_f32(lora_ctx, scaling);
  4351. ggml_set_name(scale_tensor, "scale_tensor");
  4352. BA = ggml_scale_inplace(lora_ctx, BA, scale_tensor);
  4353. offload_func(BA);
  4354. ggml_set_name(BA, "BA_scaled");
  4355. }
  4356. ggml_tensor * r;
  4357. if (base_t == dest_t) {
  4358. r = ggml_add_inplace(lora_ctx, dest_t, BA);
  4359. offload_func_force_inplace(r);
  4360. ggml_set_name(r, "r_add_inplace");
  4361. }
  4362. else {
  4363. r = ggml_add(lora_ctx, base_t, BA);
  4364. offload_func(r);
  4365. ggml_set_name(r, "r_add");
  4366. r = ggml_cpy(lora_ctx, r, dest_t);
  4367. offload_func(r);
  4368. ggml_set_name(r, "r_cpy");
  4369. }
  4370. struct ggml_cgraph gf = ggml_build_forward(r);
  4371. ggml_graph_compute_helper(work_buffer, &gf, n_threads);
  4372. // we won't need these tensors again, reset the context to save memory
  4373. ggml_free(lora_ctx);
  4374. lora_ctx = ggml_init(params);
  4375. lora_tensors.clear();
  4376. n_tensors++;
  4377. if (n_tensors % 4 == 0) {
  4378. LLAMA_LOG_INFO(".");
  4379. }
  4380. }
  4381. }
  4382. // TODO: this should be in a destructor, it will leak on failure
  4383. ggml_free(lora_ctx);
  4384. if (base_ctx) {
  4385. ggml_free(base_ctx);
  4386. }
  4387. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  4388. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  4389. return 0;
  4390. }
  4391. //
  4392. // interface implementation
  4393. //
  4394. struct llama_context_params llama_context_default_params() {
  4395. struct llama_context_params result = {
  4396. /*.seed =*/ LLAMA_DEFAULT_SEED,
  4397. /*.n_ctx =*/ 512,
  4398. /*.n_batch =*/ 512,
  4399. /*.gpu_layers =*/ 0,
  4400. /*.main_gpu =*/ 0,
  4401. /*.tensor_split =*/ nullptr,
  4402. /*.rope_freq_base =*/ 10000.0f,
  4403. /*.rope_freq_scale =*/ 1.0f,
  4404. /*.progress_callback =*/ nullptr,
  4405. /*.progress_callback_user_data =*/ nullptr,
  4406. /*.low_vram =*/ false,
  4407. /*.mul_mat_q =*/ true,
  4408. /*.f16_kv =*/ true,
  4409. /*.logits_all =*/ false,
  4410. /*.vocab_only =*/ false,
  4411. /*.use_mmap =*/ true,
  4412. /*.use_mlock =*/ false,
  4413. /*.embedding =*/ false,
  4414. };
  4415. return result;
  4416. }
  4417. struct llama_model_quantize_params llama_model_quantize_default_params() {
  4418. struct llama_model_quantize_params result = {
  4419. /*.nthread =*/ 0,
  4420. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  4421. /*.allow_requantize =*/ false,
  4422. /*.quantize_output_tensor =*/ true,
  4423. /*.only_copy =*/ false,
  4424. };
  4425. return result;
  4426. }
  4427. int llama_max_devices(void) {
  4428. return LLAMA_MAX_DEVICES;
  4429. }
  4430. bool llama_mmap_supported(void) {
  4431. return llama_mmap::SUPPORTED;
  4432. }
  4433. bool llama_mlock_supported(void) {
  4434. return llama_mlock::SUPPORTED;
  4435. }
  4436. void llama_backend_init(bool numa) {
  4437. ggml_time_init();
  4438. // needed to initialize f16 tables
  4439. {
  4440. struct ggml_init_params params = { 0, NULL, false };
  4441. struct ggml_context * ctx = ggml_init(params);
  4442. ggml_free(ctx);
  4443. }
  4444. if (numa) {
  4445. ggml_numa_init();
  4446. }
  4447. #ifdef GGML_USE_MPI
  4448. ggml_mpi_backend_init();
  4449. #endif
  4450. }
  4451. void llama_backend_free(void) {
  4452. #ifdef GGML_USE_MPI
  4453. ggml_mpi_backend_free();
  4454. #endif
  4455. }
  4456. int64_t llama_time_us(void) {
  4457. return ggml_time_us();
  4458. }
  4459. struct llama_model * llama_load_model_from_file(
  4460. const char * path_model,
  4461. struct llama_context_params params) {
  4462. ggml_time_init();
  4463. llama_model * model = new llama_model;
  4464. ggml_type memory_type = params.f16_kv ? GGML_TYPE_F16 : GGML_TYPE_F32;
  4465. unsigned cur_percentage = 0;
  4466. if (params.progress_callback == NULL) {
  4467. params.progress_callback_user_data = &cur_percentage;
  4468. params.progress_callback = [](float progress, void * ctx) {
  4469. unsigned * cur_percentage_p = (unsigned *) ctx;
  4470. unsigned percentage = (unsigned) (100 * progress);
  4471. while (percentage > *cur_percentage_p) {
  4472. *cur_percentage_p = percentage;
  4473. LLAMA_LOG_INFO(".");
  4474. if (percentage >= 100) {
  4475. LLAMA_LOG_INFO("\n");
  4476. }
  4477. }
  4478. };
  4479. }
  4480. if (!llama_model_load(path_model, *model, params.n_ctx, params.n_batch, params.n_gpu_layers,
  4481. params.main_gpu, params.tensor_split, params.mul_mat_q, params.rope_freq_base, params.rope_freq_scale,
  4482. params.low_vram, memory_type, params.use_mmap, params.use_mlock, params.vocab_only,
  4483. params.progress_callback, params.progress_callback_user_data)) {
  4484. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  4485. delete model;
  4486. return nullptr;
  4487. }
  4488. return model;
  4489. }
  4490. void llama_free_model(struct llama_model * model) {
  4491. delete model;
  4492. }
  4493. struct llama_context * llama_new_context_with_model(
  4494. struct llama_model * model,
  4495. struct llama_context_params params) {
  4496. if (!model) {
  4497. return nullptr;
  4498. }
  4499. llama_context * ctx = new llama_context(*model);
  4500. if (params.seed == LLAMA_DEFAULT_SEED) {
  4501. params.seed = time(NULL);
  4502. }
  4503. ctx->rng = std::mt19937(params.seed);
  4504. ctx->logits_all = params.logits_all;
  4505. ggml_type memory_type = params.f16_kv ? GGML_TYPE_F16 : GGML_TYPE_F32;
  4506. // reserve memory for context buffers
  4507. if (!params.vocab_only) {
  4508. if (!llama_kv_cache_init(ctx->model.hparams, ctx->kv_self, memory_type, ctx->model.hparams.n_ctx, params.n_gpu_layers)) {
  4509. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  4510. llama_free(ctx);
  4511. return nullptr;
  4512. }
  4513. {
  4514. const size_t memory_size = ggml_nbytes(ctx->kv_self.k) + ggml_nbytes(ctx->kv_self.v);
  4515. LLAMA_LOG_INFO("%s: kv self size = %7.2f MB\n", __func__, memory_size / 1024.0 / 1024.0);
  4516. }
  4517. const auto & hparams = ctx->model.hparams;
  4518. // resized during inference
  4519. if (params.logits_all) {
  4520. ctx->logits.reserve(hparams.n_ctx*hparams.n_vocab);
  4521. } else {
  4522. ctx->logits.reserve(hparams.n_vocab);
  4523. }
  4524. if (params.embedding){
  4525. ctx->embedding.resize(hparams.n_embd);
  4526. }
  4527. {
  4528. static const size_t tensor_alignment = 32;
  4529. // the compute buffer is used to store the tensor and graph structs, while the allocator buffer is used for the tensor data
  4530. ctx->buf_compute.resize(ggml_tensor_overhead()*GGML_MAX_NODES + ggml_graph_overhead());
  4531. // create measure allocator
  4532. ctx->alloc = ggml_allocr_new_measure(tensor_alignment);
  4533. // build worst-case graph
  4534. int n_tokens = std::min((int)hparams.n_ctx, params.n_batch);
  4535. int n_past = hparams.n_ctx - n_tokens;
  4536. llama_token token = llama_token_bos(ctx); // not actually used by llama_build_graph, but required to choose between token and embedding inputs graph
  4537. ggml_cgraph * gf = llama_build_graph(*ctx, &token, NULL, n_tokens, n_past);
  4538. #ifdef GGML_USE_METAL
  4539. if (params.n_gpu_layers > 0) {
  4540. ctx->ctx_metal = ggml_metal_init(1);
  4541. if (!ctx->ctx_metal) {
  4542. LLAMA_LOG_ERROR("%s: ggml_metal_init() failed\n", __func__);
  4543. llama_free(ctx);
  4544. return NULL;
  4545. }
  4546. ggml_metal_graph_find_concurrency(ctx->ctx_metal, gf, false);
  4547. ggml_allocr_set_parse_seq(ctx->alloc, ggml_metal_get_concur_list(ctx->ctx_metal), ggml_metal_if_optimized(ctx->ctx_metal));
  4548. }
  4549. #endif
  4550. // measure memory requirements for the graph
  4551. size_t alloc_size = ggml_allocr_alloc_graph(ctx->alloc, gf) + tensor_alignment;
  4552. LLAMA_LOG_INFO("%s: compute buffer total size = %7.2f MB\n", __func__, (ctx->buf_compute.size + alloc_size) / 1024.0 / 1024.0);
  4553. // recreate allocator with exact memory requirements
  4554. ggml_allocr_free(ctx->alloc);
  4555. ctx->buf_alloc.resize(alloc_size);
  4556. ctx->alloc = ggml_allocr_new(ctx->buf_alloc.data, ctx->buf_alloc.size, tensor_alignment);
  4557. #ifdef GGML_USE_METAL
  4558. if (ctx->ctx_metal) {
  4559. ggml_allocr_set_parse_seq(ctx->alloc, ggml_metal_get_concur_list(ctx->ctx_metal), ggml_metal_if_optimized(ctx->ctx_metal));
  4560. }
  4561. #endif
  4562. #ifdef GGML_USE_CUBLAS
  4563. if (params.low_vram) {
  4564. LLAMA_LOG_INFO("%s: not allocating a VRAM scratch buffer due to low VRAM option\n", __func__);
  4565. ggml_cuda_set_scratch_size(0); // disable scratch
  4566. } else {
  4567. ggml_cuda_set_scratch_size(alloc_size);
  4568. LLAMA_LOG_INFO("%s: VRAM scratch buffer: %.2f MB\n", __func__, alloc_size / 1024.0 / 1024.0);
  4569. }
  4570. #endif
  4571. }
  4572. }
  4573. #ifdef GGML_USE_METAL
  4574. if (params.n_gpu_layers > 0) {
  4575. // this allocates all Metal resources and memory buffers
  4576. void * data_ptr = NULL;
  4577. size_t data_size = 0;
  4578. if (params.use_mmap) {
  4579. data_ptr = ctx->model.mapping->addr;
  4580. data_size = ctx->model.mapping->size;
  4581. } else {
  4582. data_ptr = ggml_get_mem_buffer(ctx->model.ctx);
  4583. data_size = ggml_get_mem_size (ctx->model.ctx);
  4584. }
  4585. const size_t max_size = ggml_get_max_tensor_size(ctx->model.ctx);
  4586. LLAMA_LOG_INFO("%s: max tensor size = %8.2f MB\n", __func__, max_size/1024.0/1024.0);
  4587. #define LLAMA_METAL_CHECK_BUF(result) \
  4588. if (!(result)) { \
  4589. LLAMA_LOG_ERROR("%s: failed to add buffer\n", __func__); \
  4590. llama_free(ctx); \
  4591. return NULL; \
  4592. }
  4593. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "data", data_ptr, data_size, max_size));
  4594. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "eval", ctx->buf_compute.data, ctx->buf_compute.size, 0));
  4595. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "kv", ctx->kv_self.buf.data, ctx->kv_self.buf.size, 0));
  4596. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "alloc", ctx->buf_alloc.data, ctx->buf_alloc.size, 0));
  4597. #undef LLAMA_METAL_CHECK_BUF
  4598. }
  4599. #endif
  4600. #ifdef GGML_USE_MPI
  4601. ctx->ctx_mpi = ggml_mpi_init();
  4602. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  4603. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  4604. const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  4605. while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  4606. llama_backend_free();
  4607. exit(1);
  4608. }
  4609. #endif
  4610. return ctx;
  4611. }
  4612. struct llama_context * llama_init_from_file(
  4613. const char * path_model,
  4614. struct llama_context_params params) {
  4615. struct llama_model * model = llama_load_model_from_file(path_model, params);
  4616. if (!model) {
  4617. return nullptr;
  4618. }
  4619. struct llama_context * ctx = llama_new_context_with_model(model, params);
  4620. ctx->model_owner = true;
  4621. return ctx;
  4622. }
  4623. void llama_free(struct llama_context * ctx) {
  4624. delete ctx;
  4625. }
  4626. int llama_n_vocab(const struct llama_context * ctx) {
  4627. return ctx->model.vocab.id_to_token.size();
  4628. }
  4629. int llama_n_ctx(const struct llama_context * ctx) {
  4630. return ctx->model.hparams.n_ctx;
  4631. }
  4632. int llama_n_embd(const struct llama_context * ctx) {
  4633. return ctx->model.hparams.n_embd;
  4634. }
  4635. enum llama_vocab_type llama_vocab_type(const struct llama_context * ctx) {
  4636. return ctx->model.vocab.type;
  4637. }
  4638. int llama_model_n_vocab(const struct llama_model * model) {
  4639. return model->vocab.id_to_token.size();
  4640. }
  4641. int llama_model_n_ctx(const struct llama_model * model) {
  4642. return model->hparams.n_ctx;
  4643. }
  4644. int llama_model_n_embd(const struct llama_model * model) {
  4645. return model->hparams.n_embd;
  4646. }
  4647. int llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  4648. return snprintf(buf, buf_size, "%s %s %s",
  4649. model->name.c_str(),
  4650. llama_model_type_name(model->type),
  4651. llama_model_ftype_name(model->ftype).c_str());
  4652. }
  4653. uint64_t llama_model_size(const struct llama_model * model) {
  4654. uint64_t size = 0;
  4655. for (const auto & it : model->tensors_by_name) {
  4656. size += ggml_nbytes(it.second);
  4657. }
  4658. return size;
  4659. }
  4660. uint64_t llama_model_n_params(const struct llama_model * model) {
  4661. uint64_t nparams = 0;
  4662. for (const auto & it : model->tensors_by_name) {
  4663. nparams += ggml_nelements(it.second);
  4664. }
  4665. return nparams;
  4666. }
  4667. int llama_model_quantize(
  4668. const char * fname_inp,
  4669. const char * fname_out,
  4670. const llama_model_quantize_params * params) {
  4671. try {
  4672. llama_model_quantize_internal(fname_inp, fname_out, params);
  4673. return 0;
  4674. } catch (const std::exception & err) {
  4675. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  4676. return 1;
  4677. }
  4678. }
  4679. int llama_apply_lora_from_file(struct llama_context * ctx, const char * path_lora, const char * path_base_model, int n_threads) {
  4680. try {
  4681. return llama_apply_lora_from_file_internal(ctx->model, path_lora, path_base_model, n_threads);
  4682. } catch (const std::exception & err) {
  4683. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  4684. return 1;
  4685. }
  4686. }
  4687. int llama_model_apply_lora_from_file(const struct llama_model * model, const char * path_lora, const char * path_base_model, int n_threads) {
  4688. try {
  4689. return llama_apply_lora_from_file_internal(*model, path_lora, path_base_model, n_threads);
  4690. } catch (const std::exception & err) {
  4691. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  4692. return 1;
  4693. }
  4694. }
  4695. int llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  4696. return ctx->kv_self.n;
  4697. }
  4698. #define LLAMA_MAX_RNG_STATE (64*1024)
  4699. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  4700. if (seed == LLAMA_DEFAULT_SEED) {
  4701. seed = time(NULL);
  4702. }
  4703. ctx->rng.seed(seed);
  4704. }
  4705. // Returns the *maximum* size of the state
  4706. size_t llama_get_state_size(const struct llama_context * ctx) {
  4707. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  4708. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  4709. const size_t s_rng_size = sizeof(size_t);
  4710. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  4711. const size_t s_logits_capacity = sizeof(size_t);
  4712. const size_t s_logits_size = sizeof(size_t);
  4713. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  4714. const size_t s_embedding_size = sizeof(size_t);
  4715. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  4716. const size_t s_kv_size = sizeof(size_t);
  4717. const size_t s_kv_ntok = sizeof(int);
  4718. const size_t s_kv = ctx->kv_self.buf.size;
  4719. const size_t s_total = (
  4720. + s_rng_size
  4721. + s_rng
  4722. + s_logits_capacity
  4723. + s_logits_size
  4724. + s_logits
  4725. + s_embedding_size
  4726. + s_embedding
  4727. + s_kv_size
  4728. + s_kv_ntok
  4729. + s_kv
  4730. );
  4731. return s_total;
  4732. }
  4733. // llama_context_data
  4734. struct llama_data_context {
  4735. virtual void write(const void * src, size_t size) = 0;
  4736. virtual size_t get_size_written() = 0;
  4737. virtual ~llama_data_context() = default;
  4738. };
  4739. struct llama_data_buffer_context : llama_data_context {
  4740. uint8_t * ptr;
  4741. size_t size_written = 0;
  4742. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  4743. void write(const void * src, size_t size) override {
  4744. memcpy(ptr, src, size);
  4745. ptr += size;
  4746. size_written += size;
  4747. }
  4748. size_t get_size_written() override {
  4749. return size_written;
  4750. }
  4751. };
  4752. struct llama_data_file_context : llama_data_context {
  4753. llama_file * file;
  4754. size_t size_written = 0;
  4755. llama_data_file_context(llama_file * f) : file(f) {}
  4756. void write(const void * src, size_t size) override {
  4757. file->write_raw(src, size);
  4758. size_written += size;
  4759. }
  4760. size_t get_size_written() override {
  4761. return size_written;
  4762. }
  4763. };
  4764. /** copy state data into either a buffer or file depending on the passed in context
  4765. *
  4766. * file context:
  4767. * llama_file file("/path", "wb");
  4768. * llama_data_file_context data_ctx(&file);
  4769. * llama_copy_state_data(ctx, &data_ctx);
  4770. *
  4771. * buffer context:
  4772. * std::vector<uint8_t> buf(max_size, 0);
  4773. * llama_data_buffer_context data_ctx(&buf.data());
  4774. * llama_copy_state_data(ctx, &data_ctx);
  4775. *
  4776. */
  4777. void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  4778. // copy rng
  4779. {
  4780. std::stringstream rng_ss;
  4781. rng_ss << ctx->rng;
  4782. const size_t rng_size = rng_ss.str().size();
  4783. char rng_buf[LLAMA_MAX_RNG_STATE];
  4784. memset(&rng_buf[0], 0, LLAMA_MAX_RNG_STATE);
  4785. memcpy(&rng_buf[0], rng_ss.str().data(), rng_ss.str().size());
  4786. data_ctx->write(&rng_size, sizeof(rng_size));
  4787. data_ctx->write(&rng_buf[0], LLAMA_MAX_RNG_STATE);
  4788. }
  4789. // copy logits
  4790. {
  4791. const size_t logits_cap = ctx->logits.capacity();
  4792. const size_t logits_size = ctx->logits.size();
  4793. data_ctx->write(&logits_cap, sizeof(logits_cap));
  4794. data_ctx->write(&logits_size, sizeof(logits_size));
  4795. if (logits_size) {
  4796. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  4797. }
  4798. // If there is a gap between the size and the capacity, write padding
  4799. size_t padding_size = (logits_cap - logits_size) * sizeof(float);
  4800. if (padding_size > 0) {
  4801. std::vector<uint8_t> padding(padding_size, 0); // Create a buffer filled with zeros
  4802. data_ctx->write(padding.data(), padding_size);
  4803. }
  4804. }
  4805. // copy embeddings
  4806. {
  4807. const size_t embedding_size = ctx->embedding.size();
  4808. data_ctx->write(&embedding_size, sizeof(embedding_size));
  4809. if (embedding_size) {
  4810. data_ctx->write(ctx->embedding.data(), embedding_size * sizeof(float));
  4811. }
  4812. }
  4813. // copy kv cache
  4814. {
  4815. const auto & kv_self = ctx->kv_self;
  4816. const auto & hparams = ctx->model.hparams;
  4817. const int n_layer = hparams.n_layer;
  4818. const int n_embd = hparams.n_embd_gqa();
  4819. const int n_ctx = hparams.n_ctx;
  4820. const size_t kv_size = kv_self.buf.size;
  4821. const int kv_ntok = llama_get_kv_cache_token_count(ctx);
  4822. data_ctx->write(&kv_size, sizeof(kv_size));
  4823. data_ctx->write(&kv_ntok, sizeof(kv_ntok));
  4824. if (kv_size) {
  4825. const size_t elt_size = ggml_element_size(kv_self.k);
  4826. ggml_context * cpy_ctx = ggml_init({ 4096, NULL, /* no_alloc */ true });
  4827. ggml_cgraph gf{};
  4828. ggml_tensor * kout3d = ggml_new_tensor_3d(cpy_ctx, kv_self.k->type, n_embd, kv_ntok, n_layer);
  4829. std::vector<uint8_t> kout3d_data(ggml_nbytes(kout3d), 0);
  4830. kout3d->data = kout3d_data.data();
  4831. ggml_tensor * vout3d = ggml_new_tensor_3d(cpy_ctx, kv_self.v->type, kv_ntok, n_embd, n_layer);
  4832. std::vector<uint8_t> vout3d_data(ggml_nbytes(vout3d), 0);
  4833. vout3d->data = vout3d_data.data();
  4834. ggml_tensor * k3d = ggml_view_3d(cpy_ctx, kv_self.k,
  4835. n_embd, kv_ntok, n_layer,
  4836. elt_size*n_embd, elt_size*n_embd*n_ctx, 0);
  4837. ggml_tensor * v3d = ggml_view_3d(cpy_ctx, kv_self.v,
  4838. kv_ntok, n_embd, n_layer,
  4839. elt_size*n_ctx, elt_size*n_ctx*n_embd, 0);
  4840. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, k3d, kout3d));
  4841. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, v3d, vout3d));
  4842. ggml_graph_compute_helper(ctx->work_buffer, &gf, /*n_threads*/ 1);
  4843. ggml_free(cpy_ctx);
  4844. // our data is now in the kout3d_data and vout3d_data buffers
  4845. // write them to file
  4846. data_ctx->write(kout3d_data.data(), kout3d_data.size());
  4847. data_ctx->write(vout3d_data.data(), vout3d_data.size());
  4848. }
  4849. }
  4850. }
  4851. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  4852. llama_data_buffer_context data_ctx(dst);
  4853. llama_copy_state_data_internal(ctx, &data_ctx);
  4854. return data_ctx.get_size_written();
  4855. }
  4856. // Sets the state reading from the specified source address
  4857. size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src) {
  4858. uint8_t * inp = src;
  4859. // set rng
  4860. {
  4861. size_t rng_size;
  4862. char rng_buf[LLAMA_MAX_RNG_STATE];
  4863. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  4864. memcpy(&rng_buf[0], inp, LLAMA_MAX_RNG_STATE); inp += LLAMA_MAX_RNG_STATE;
  4865. std::stringstream rng_ss;
  4866. rng_ss.str(std::string(&rng_buf[0], rng_size));
  4867. rng_ss >> ctx->rng;
  4868. GGML_ASSERT(rng_ss.fail() == false);
  4869. }
  4870. // set logits
  4871. {
  4872. size_t logits_cap;
  4873. size_t logits_size;
  4874. memcpy(&logits_cap, inp, sizeof(logits_cap)); inp += sizeof(logits_cap);
  4875. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  4876. GGML_ASSERT(ctx->logits.capacity() == logits_cap);
  4877. if (logits_size) {
  4878. ctx->logits.resize(logits_size);
  4879. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  4880. }
  4881. inp += logits_cap * sizeof(float);
  4882. }
  4883. // set embeddings
  4884. {
  4885. size_t embedding_size;
  4886. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  4887. GGML_ASSERT(ctx->embedding.capacity() == embedding_size);
  4888. if (embedding_size) {
  4889. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  4890. inp += embedding_size * sizeof(float);
  4891. }
  4892. }
  4893. // set kv cache
  4894. {
  4895. const auto & kv_self = ctx->kv_self;
  4896. const auto & hparams = ctx->model.hparams;
  4897. const int n_layer = hparams.n_layer;
  4898. const int n_embd = hparams.n_embd_gqa();
  4899. const int n_ctx = hparams.n_ctx;
  4900. size_t kv_size;
  4901. int kv_ntok;
  4902. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  4903. memcpy(&kv_ntok, inp, sizeof(kv_ntok)); inp += sizeof(kv_ntok);
  4904. if (kv_size) {
  4905. GGML_ASSERT(kv_self.buf.size == kv_size);
  4906. const size_t elt_size = ggml_element_size(kv_self.k);
  4907. ggml_context * cpy_ctx = ggml_init({ 4096, NULL, /* no_alloc */ true });
  4908. ggml_cgraph gf{};
  4909. ggml_tensor * kin3d = ggml_new_tensor_3d(cpy_ctx, kv_self.k->type, n_embd, kv_ntok, n_layer);
  4910. kin3d->data = (void *) inp;
  4911. inp += ggml_nbytes(kin3d);
  4912. ggml_tensor * vin3d = ggml_new_tensor_3d(cpy_ctx, kv_self.v->type, kv_ntok, n_embd, n_layer);
  4913. vin3d->data = (void *) inp;
  4914. inp += ggml_nbytes(vin3d);
  4915. ggml_tensor * k3d = ggml_view_3d(cpy_ctx, kv_self.k,
  4916. n_embd, kv_ntok, n_layer,
  4917. elt_size*n_embd, elt_size*n_embd*n_ctx, 0);
  4918. ggml_tensor * v3d = ggml_view_3d(cpy_ctx, kv_self.v,
  4919. kv_ntok, n_embd, n_layer,
  4920. elt_size*n_ctx, elt_size*n_ctx*n_embd, 0);
  4921. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, kin3d, k3d));
  4922. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, vin3d, v3d));
  4923. ggml_graph_compute_helper(ctx->work_buffer, &gf, /*n_threads*/ 1);
  4924. ggml_free(cpy_ctx);
  4925. }
  4926. ctx->kv_self.n = kv_ntok;
  4927. }
  4928. const size_t nread = inp - src;
  4929. const size_t max_size = llama_get_state_size(ctx);
  4930. GGML_ASSERT(nread <= max_size);
  4931. return nread;
  4932. }
  4933. 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) {
  4934. llama_file file(path_session, "rb");
  4935. // sanity checks
  4936. {
  4937. const uint32_t magic = file.read_u32();
  4938. const uint32_t version = file.read_u32();
  4939. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  4940. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  4941. return false;
  4942. }
  4943. llama_hparams session_hparams;
  4944. file.read_raw(&session_hparams, sizeof(llama_hparams));
  4945. if (session_hparams != ctx->model.hparams) {
  4946. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  4947. return false;
  4948. }
  4949. }
  4950. // load the prompt
  4951. {
  4952. const uint32_t n_token_count = file.read_u32();
  4953. if (n_token_count > n_token_capacity) {
  4954. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  4955. return false;
  4956. }
  4957. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  4958. *n_token_count_out = n_token_count;
  4959. }
  4960. // restore the context state
  4961. {
  4962. const size_t n_state_size_cur = file.size - file.tell();
  4963. const size_t n_state_size_max = llama_get_state_size(ctx);
  4964. if (n_state_size_cur > n_state_size_max) {
  4965. 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);
  4966. return false;
  4967. }
  4968. std::vector<uint8_t> state_data(n_state_size_max);
  4969. file.read_raw(state_data.data(), n_state_size_cur);
  4970. llama_set_state_data(ctx, state_data.data());
  4971. }
  4972. return true;
  4973. }
  4974. 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) {
  4975. try {
  4976. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  4977. } catch (const std::exception & err) {
  4978. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  4979. return false;
  4980. }
  4981. }
  4982. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  4983. llama_file file(path_session, "wb");
  4984. file.write_u32(LLAMA_SESSION_MAGIC);
  4985. file.write_u32(LLAMA_SESSION_VERSION);
  4986. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  4987. // save the prompt
  4988. file.write_u32((uint32_t) n_token_count);
  4989. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  4990. // save the context state using stream saving
  4991. llama_data_file_context data_ctx(&file);
  4992. llama_copy_state_data_internal(ctx, &data_ctx);
  4993. return true;
  4994. }
  4995. int llama_eval(
  4996. struct llama_context * ctx,
  4997. const llama_token * tokens,
  4998. int n_tokens,
  4999. int n_past,
  5000. int n_threads) {
  5001. if (!llama_eval_internal(*ctx, tokens, nullptr, n_tokens, n_past, n_threads, nullptr)) {
  5002. LLAMA_LOG_ERROR("%s: failed to eval\n", __func__);
  5003. return 1;
  5004. }
  5005. // get a more accurate load time, upon first eval
  5006. // TODO: fix this
  5007. if (!ctx->has_evaluated_once) {
  5008. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  5009. ctx->has_evaluated_once = true;
  5010. }
  5011. return 0;
  5012. }
  5013. int llama_eval_embd(
  5014. struct llama_context * ctx,
  5015. const float * embd,
  5016. int n_tokens,
  5017. int n_past,
  5018. int n_threads) {
  5019. if (!llama_eval_internal(*ctx, nullptr, embd, n_tokens, n_past, n_threads, nullptr)) {
  5020. LLAMA_LOG_ERROR("%s: failed to eval\n", __func__);
  5021. return 1;
  5022. }
  5023. // get a more accurate load time, upon first eval
  5024. // TODO: fix this
  5025. if (!ctx->has_evaluated_once) {
  5026. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  5027. ctx->has_evaluated_once = true;
  5028. }
  5029. return 0;
  5030. }
  5031. int llama_eval_export(struct llama_context * ctx, const char * fname) {
  5032. const int n_batch = 1;
  5033. const int n_ctx = 512 - n_batch;
  5034. const std::vector<llama_token> tmp(n_batch, llama_token_bos(ctx));
  5035. if (!llama_eval_internal(*ctx, tmp.data(), nullptr, tmp.size(), n_ctx, 1, fname)) {
  5036. LLAMA_LOG_ERROR("%s: failed to eval\n", __func__);
  5037. return 1;
  5038. }
  5039. return 0;
  5040. }
  5041. float * llama_get_logits(struct llama_context * ctx) {
  5042. return ctx->logits.data();
  5043. }
  5044. float * llama_get_embeddings(struct llama_context * ctx) {
  5045. return ctx->embedding.data();
  5046. }
  5047. const char * llama_token_get_text(const struct llama_context * ctx, llama_token token) {
  5048. return ctx->model.vocab.id_to_token[token].text.c_str();
  5049. }
  5050. float llama_token_get_score(const struct llama_context * ctx, llama_token token) {
  5051. return ctx->model.vocab.id_to_token[token].score;
  5052. }
  5053. llama_token_type llama_token_get_type(const struct llama_context * ctx, llama_token token) {
  5054. return ctx->model.vocab.id_to_token[token].type;
  5055. }
  5056. llama_token llama_token_bos(const struct llama_context * ctx) {
  5057. return ctx->model.vocab.special_bos_id;
  5058. }
  5059. llama_token llama_token_eos(const struct llama_context * ctx) {
  5060. return ctx->model.vocab.special_eos_id;
  5061. }
  5062. llama_token llama_token_nl(const struct llama_context * ctx) {
  5063. return ctx->model.vocab.linefeed_id;
  5064. }
  5065. int llama_tokenize(
  5066. struct llama_context * ctx,
  5067. const char * text,
  5068. llama_token * tokens,
  5069. int n_max_tokens,
  5070. bool add_bos) {
  5071. return llama_tokenize_with_model(&ctx->model, text, tokens, n_max_tokens, add_bos);
  5072. }
  5073. int llama_tokenize_with_model(
  5074. const struct llama_model * model,
  5075. const char * text,
  5076. llama_token * tokens,
  5077. int n_max_tokens,
  5078. bool add_bos) {
  5079. auto res = llama_tokenize_internal(model->vocab, text, add_bos);
  5080. if (n_max_tokens < (int) res.size()) {
  5081. LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  5082. return -((int) res.size());
  5083. }
  5084. for (size_t i = 0; i < res.size(); i++) {
  5085. tokens[i] = res[i];
  5086. }
  5087. return res.size();
  5088. }
  5089. int llama_token_to_piece(const struct llama_context * ctx, llama_token token, char * buf, int length) {
  5090. return llama_token_to_piece_with_model(&ctx->model, token, buf, length);
  5091. }
  5092. // does not write null-terminator to buf
  5093. int llama_token_to_piece_with_model(const struct llama_model * model, llama_token token, char * buf, int length) {
  5094. if (0 <= token && token < llama_model_n_vocab(model)) {
  5095. if (llama_is_normal_token(model->vocab, token)) {
  5096. std::string result = model->vocab.id_to_token[token].text;
  5097. if (llama_vocab_get_type(model->vocab) == LLAMA_VOCAB_TYPE_SPM) {
  5098. llama_unescape_whitespace(result);
  5099. }
  5100. if (length < (int) result.length()) {
  5101. return -result.length();
  5102. }
  5103. memcpy(buf, result.c_str(), result.length());
  5104. return result.length();
  5105. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  5106. if (length < 3) {
  5107. return -3;
  5108. }
  5109. buf[0] = '\xe2';
  5110. buf[1] = '\x96';
  5111. buf[2] = '\x85';
  5112. return 3;
  5113. } else if (llama_is_control_token(model->vocab, token)) {
  5114. ;
  5115. } else if (llama_is_byte_token(model->vocab, token)) {
  5116. if (length < 1) {
  5117. return -1;
  5118. }
  5119. buf[0] = llama_token_to_byte(model->vocab, token);
  5120. return 1;
  5121. }
  5122. }
  5123. return 0;
  5124. }
  5125. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  5126. struct llama_timings result = {
  5127. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  5128. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  5129. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  5130. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  5131. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  5132. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  5133. /*.n_sample =*/ std::max(1, ctx->n_sample),
  5134. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  5135. /*.n_eval =*/ std::max(1, ctx->n_eval),
  5136. };
  5137. return result;
  5138. }
  5139. void llama_print_timings(struct llama_context * ctx) {
  5140. const llama_timings timings = llama_get_timings(ctx);
  5141. LLAMA_LOG_INFO("\n");
  5142. LLAMA_LOG_INFO("%s: load time = %8.2f ms\n", __func__, timings.t_load_ms);
  5143. LLAMA_LOG_INFO("%s: sample time = %8.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  5144. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  5145. LLAMA_LOG_INFO("%s: prompt eval time = %8.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  5146. __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);
  5147. LLAMA_LOG_INFO("%s: eval time = %8.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  5148. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  5149. LLAMA_LOG_INFO("%s: total time = %8.2f ms\n", __func__, (timings.t_end_ms - timings.t_start_ms));
  5150. }
  5151. void llama_reset_timings(struct llama_context * ctx) {
  5152. ctx->t_start_us = ggml_time_us();
  5153. ctx->t_sample_us = ctx->n_sample = 0;
  5154. ctx->t_eval_us = ctx->n_eval = 0;
  5155. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  5156. }
  5157. const char * llama_print_system_info(void) {
  5158. static std::string s;
  5159. s = "";
  5160. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  5161. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  5162. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  5163. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  5164. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  5165. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  5166. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  5167. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  5168. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  5169. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  5170. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  5171. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  5172. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  5173. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  5174. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  5175. return s.c_str();
  5176. }
  5177. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  5178. fprintf(stream, "\n");
  5179. fprintf(stream, "###########\n");
  5180. fprintf(stream, "# Timings #\n");
  5181. fprintf(stream, "###########\n");
  5182. fprintf(stream, "\n");
  5183. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  5184. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  5185. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  5186. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  5187. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  5188. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  5189. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  5190. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  5191. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  5192. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  5193. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  5194. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  5195. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  5196. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  5197. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  5198. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  5199. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  5200. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  5201. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  5202. }
  5203. // For internal test use
  5204. const std::vector<std::pair<std::string, struct ggml_tensor *>>& llama_internal_get_tensor_map(struct llama_context * ctx) {
  5205. return ctx->model.tensors_by_name;
  5206. }
  5207. void llama_log_set(llama_log_callback log_callback, void * user_data) {
  5208. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  5209. g_state.log_callback_user_data = user_data;
  5210. }
  5211. static void llama_log_internal_v(llama_log_level level, const char * format, va_list args) {
  5212. va_list args_copy;
  5213. va_copy(args_copy, args);
  5214. char buffer[128];
  5215. int len = vsnprintf(buffer, 128, format, args);
  5216. if (len < 128) {
  5217. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  5218. } else {
  5219. char* buffer2 = new char[len+1];
  5220. vsnprintf(buffer2, len+1, format, args_copy);
  5221. buffer2[len] = 0;
  5222. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  5223. delete[] buffer2;
  5224. }
  5225. va_end(args_copy);
  5226. }
  5227. static void llama_log_internal(llama_log_level level, const char * format, ...) {
  5228. va_list args;
  5229. va_start(args, format);
  5230. llama_log_internal_v(level, format, args);
  5231. va_end(args);
  5232. }
  5233. static void llama_log_callback_default(llama_log_level level, const char * text, void * user_data) {
  5234. (void) level;
  5235. (void) user_data;
  5236. fputs(text, stderr);
  5237. fflush(stderr);
  5238. }