llama.cpp 219 KB

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