llama.cpp 172 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028
  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 <sstream>
  68. #include <thread>
  69. #include <unordered_map>
  70. #if defined(_MSC_VER)
  71. #pragma warning(disable: 4244 4267) // possible loss of data
  72. #endif
  73. // tensor names
  74. #define TN_TOKEN_EMBD "token_embd.weight"
  75. #define TN_OUTPUT_NORM "output_norm.weight"
  76. #define TN_OUTPUT "output.weight"
  77. #define TN_ATTN_NORM "blk.%d.attn_norm.weight"
  78. #define TN_ATTN_Q "blk.%d.attn_q.weight"
  79. #define TN_ATTN_K "blk.%d.attn_k.weight"
  80. #define TN_ATTN_V "blk.%d.attn_v.weight"
  81. #define TN_ATTN_OUTPUT "blk.%d.attn_output.weight"
  82. #define TN_FFN_NORM "blk.%d.ffn_norm.weight"
  83. #define TN_FFN_GATE "blk.%d.ffn_gate.weight"
  84. #define TN_FFN_DOWN "blk.%d.ffn_down.weight"
  85. #define TN_FFN_UP "blk.%d.ffn_up.weight"
  86. #ifdef __GNUC__
  87. #ifdef __MINGW32__
  88. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  89. #else
  90. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  91. #endif
  92. #else
  93. #define LLAMA_ATTRIBUTE_FORMAT(...)
  94. #endif
  95. //
  96. // logging
  97. //
  98. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  99. static void llama_log_internal (llama_log_level level, const char* format, ...);
  100. static void llama_log_callback_default(llama_log_level level, const char * text, void * user_data);
  101. #define LLAMA_LOG_INFO(...) llama_log_internal(LLAMA_LOG_LEVEL_INFO , __VA_ARGS__)
  102. #define LLAMA_LOG_WARN(...) llama_log_internal(LLAMA_LOG_LEVEL_WARN , __VA_ARGS__)
  103. #define LLAMA_LOG_ERROR(...) llama_log_internal(LLAMA_LOG_LEVEL_ERROR, __VA_ARGS__)
  104. //
  105. // helpers
  106. //
  107. static void zeros(std::ofstream & file, size_t n) {
  108. char zero = 0;
  109. for (size_t i = 0; i < n; ++i) {
  110. file.write(&zero, 1);
  111. }
  112. }
  113. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  114. static std::string format(const char * fmt, ...) {
  115. va_list ap;
  116. va_list ap2;
  117. va_start(ap, fmt);
  118. va_copy(ap2, ap);
  119. int size = vsnprintf(NULL, 0, fmt, ap);
  120. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  121. std::vector<char> buf(size + 1);
  122. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  123. GGML_ASSERT(size2 == size);
  124. va_end(ap2);
  125. va_end(ap);
  126. return std::string(buf.data(), size);
  127. }
  128. //
  129. // ggml helpers
  130. //
  131. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  132. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  133. if (plan.work_size > 0) {
  134. buf.resize(plan.work_size);
  135. plan.work_data = buf.data();
  136. }
  137. ggml_graph_compute(graph, &plan);
  138. }
  139. //
  140. // llama helpers
  141. //
  142. #ifdef GGML_USE_CUBLAS
  143. # define llama_host_malloc(n) ggml_cuda_host_malloc(n)
  144. # define llama_host_free(data) ggml_cuda_host_free(data)
  145. #elif GGML_USE_METAL
  146. # define llama_host_malloc(n) ggml_metal_host_malloc(n)
  147. # define llama_host_free(data) ggml_metal_host_free(data)
  148. #else
  149. # define llama_host_malloc(n) malloc(n)
  150. # define llama_host_free(data) free(data)
  151. #endif
  152. #if defined(_WIN32)
  153. static std::string llama_format_win_err(DWORD err) {
  154. LPSTR buf;
  155. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  156. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  157. if (!size) {
  158. return "FormatMessageA failed";
  159. }
  160. std::string ret(buf, size);
  161. LocalFree(buf);
  162. return ret;
  163. }
  164. #endif
  165. struct llama_buffer {
  166. void * data = NULL;
  167. size_t size = 0;
  168. // fallback to malloc / free
  169. // useful in cases where CUDA can try to allocate PINNED memory
  170. bool fallback = false;
  171. void resize(size_t n) {
  172. llama_host_free(data);
  173. data = llama_host_malloc(n);
  174. if (!data) {
  175. fallback = true;
  176. data = malloc(n);
  177. } else {
  178. fallback = false;
  179. }
  180. GGML_ASSERT(data);
  181. size = n;
  182. }
  183. ~llama_buffer() {
  184. if (data) {
  185. if (fallback) { // NOLINT
  186. free(data);
  187. } else {
  188. llama_host_free(data);
  189. }
  190. }
  191. data = NULL;
  192. }
  193. };
  194. struct llama_file {
  195. // use FILE * so we don't have to re-open the file to mmap
  196. FILE * fp;
  197. size_t size;
  198. llama_file(const char * fname, const char * mode) {
  199. fp = std::fopen(fname, mode);
  200. if (fp == NULL) {
  201. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  202. }
  203. seek(0, SEEK_END);
  204. size = tell();
  205. seek(0, SEEK_SET);
  206. }
  207. size_t tell() const {
  208. #ifdef _WIN32
  209. __int64 ret = _ftelli64(fp);
  210. #else
  211. long ret = std::ftell(fp);
  212. #endif
  213. GGML_ASSERT(ret != -1); // this really shouldn't fail
  214. return (size_t) ret;
  215. }
  216. void seek(size_t offset, int whence) const {
  217. #ifdef _WIN32
  218. int ret = _fseeki64(fp, (__int64) offset, whence);
  219. #else
  220. int ret = std::fseek(fp, (long) offset, whence);
  221. #endif
  222. GGML_ASSERT(ret == 0); // same
  223. }
  224. void read_raw(void * ptr, size_t len) const {
  225. if (len == 0) {
  226. return;
  227. }
  228. errno = 0;
  229. std::size_t ret = std::fread(ptr, len, 1, fp);
  230. if (ferror(fp)) {
  231. throw std::runtime_error(format("read error: %s", strerror(errno)));
  232. }
  233. if (ret != 1) {
  234. throw std::runtime_error(std::string("unexpectedly reached end of file"));
  235. }
  236. }
  237. uint32_t read_u32() const {
  238. uint32_t ret;
  239. read_raw(&ret, sizeof(ret));
  240. return ret;
  241. }
  242. void write_raw(const void * ptr, size_t len) const {
  243. if (len == 0) {
  244. return;
  245. }
  246. errno = 0;
  247. size_t ret = std::fwrite(ptr, len, 1, fp);
  248. if (ret != 1) {
  249. throw std::runtime_error(format("write error: %s", strerror(errno)));
  250. }
  251. }
  252. void write_u32(std::uint32_t val) const {
  253. write_raw(&val, sizeof(val));
  254. }
  255. ~llama_file() {
  256. if (fp) {
  257. std::fclose(fp);
  258. }
  259. }
  260. };
  261. struct llama_mmap {
  262. void * addr;
  263. size_t size;
  264. llama_mmap(const llama_mmap &) = delete;
  265. #ifdef _POSIX_MAPPED_FILES
  266. static constexpr bool SUPPORTED = true;
  267. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  268. size = file->size;
  269. int fd = fileno(file->fp);
  270. int flags = MAP_SHARED;
  271. // prefetch/readahead impairs performance on NUMA systems
  272. if (numa) { prefetch = 0; }
  273. #ifdef __linux__
  274. if (prefetch) { flags |= MAP_POPULATE; }
  275. #endif
  276. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  277. if (addr == MAP_FAILED) {
  278. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  279. }
  280. if (prefetch > 0) {
  281. // Advise the kernel to preload the mapped memory
  282. if (madvise(addr, std::min(file->size, prefetch), MADV_WILLNEED)) {
  283. fprintf(stderr, "warning: madvise(.., MADV_WILLNEED) failed: %s\n",
  284. strerror(errno));
  285. }
  286. }
  287. if (numa) {
  288. // advise the kernel not to use readahead
  289. // (because the next page might not belong on the same node)
  290. if (madvise(addr, file->size, MADV_RANDOM)) {
  291. fprintf(stderr, "warning: madvise(.., MADV_RANDOM) failed: %s\n",
  292. strerror(errno));
  293. }
  294. }
  295. }
  296. ~llama_mmap() {
  297. munmap(addr, size);
  298. }
  299. #elif defined(_WIN32)
  300. static constexpr bool SUPPORTED = true;
  301. llama_mmap(struct llama_file * file, bool prefetch = true, bool numa = false) {
  302. (void) numa;
  303. size = file->size;
  304. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  305. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  306. DWORD error = GetLastError();
  307. if (hMapping == NULL) {
  308. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  309. }
  310. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  311. error = GetLastError();
  312. CloseHandle(hMapping);
  313. if (addr == NULL) {
  314. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  315. }
  316. #if _WIN32_WINNT >= _WIN32_WINNT_WIN8
  317. if (prefetch) {
  318. // Advise the kernel to preload the mapped memory
  319. WIN32_MEMORY_RANGE_ENTRY range;
  320. range.VirtualAddress = addr;
  321. range.NumberOfBytes = (SIZE_T)size;
  322. if (!PrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  323. fprintf(stderr, "warning: PrefetchVirtualMemory failed: %s\n",
  324. llama_format_win_err(GetLastError()).c_str());
  325. }
  326. }
  327. #else
  328. #pragma message("warning: You are building for pre-Windows 8; prefetch not supported")
  329. #endif // _WIN32_WINNT >= _WIN32_WINNT_WIN8
  330. }
  331. ~llama_mmap() {
  332. if (!UnmapViewOfFile(addr)) {
  333. fprintf(stderr, "warning: UnmapViewOfFile failed: %s\n",
  334. llama_format_win_err(GetLastError()).c_str());
  335. }
  336. }
  337. #else
  338. static constexpr bool SUPPORTED = false;
  339. llama_mmap(struct llama_file * file, bool prefetch = true, bool numa = false) {
  340. (void) file;
  341. (void) prefetch;
  342. (void) numa;
  343. throw std::runtime_error(std::string("mmap not supported"));
  344. }
  345. #endif
  346. };
  347. // Represents some region of memory being locked using mlock or VirtualLock;
  348. // will automatically unlock on destruction.
  349. struct llama_mlock {
  350. void * addr = NULL;
  351. size_t size = 0;
  352. bool failed_already = false;
  353. llama_mlock() {}
  354. llama_mlock(const llama_mlock &) = delete;
  355. ~llama_mlock() {
  356. if (size) {
  357. raw_unlock(addr, size);
  358. }
  359. }
  360. void init(void * ptr) {
  361. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  362. addr = ptr;
  363. }
  364. void grow_to(size_t target_size) {
  365. GGML_ASSERT(addr);
  366. if (failed_already) {
  367. return;
  368. }
  369. size_t granularity = lock_granularity();
  370. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  371. if (target_size > size) {
  372. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  373. size = target_size;
  374. } else {
  375. failed_already = true;
  376. }
  377. }
  378. }
  379. #ifdef _POSIX_MEMLOCK_RANGE
  380. static constexpr bool SUPPORTED = true;
  381. static size_t lock_granularity() {
  382. return (size_t) sysconf(_SC_PAGESIZE);
  383. }
  384. #ifdef __APPLE__
  385. #define MLOCK_SUGGESTION \
  386. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  387. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MLOCK (ulimit -l).\n"
  388. #else
  389. #define MLOCK_SUGGESTION \
  390. "Try increasing RLIMIT_MLOCK ('ulimit -l' as root).\n"
  391. #endif
  392. bool raw_lock(const void * addr, size_t size) const {
  393. if (!mlock(addr, size)) {
  394. return true;
  395. }
  396. char* errmsg = std::strerror(errno);
  397. bool suggest = (errno == ENOMEM);
  398. // Check if the resource limit is fine after all
  399. struct rlimit lock_limit;
  400. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  401. suggest = false;
  402. }
  403. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  404. suggest = false;
  405. }
  406. fprintf(stderr, "warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  407. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  408. return false;
  409. }
  410. #undef MLOCK_SUGGESTION
  411. static void raw_unlock(void * addr, size_t size) {
  412. if (munlock(addr, size)) {
  413. fprintf(stderr, "warning: failed to munlock buffer: %s\n", std::strerror(errno));
  414. }
  415. }
  416. #elif defined(_WIN32)
  417. static constexpr bool SUPPORTED = true;
  418. static size_t lock_granularity() {
  419. SYSTEM_INFO si;
  420. GetSystemInfo(&si);
  421. return (size_t) si.dwPageSize;
  422. }
  423. bool raw_lock(void * ptr, size_t len) const {
  424. for (int tries = 1; ; tries++) {
  425. if (VirtualLock(ptr, len)) {
  426. return true;
  427. }
  428. if (tries == 2) {
  429. fprintf(stderr, "warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  430. len, size, llama_format_win_err(GetLastError()).c_str());
  431. return false;
  432. }
  433. // It failed but this was only the first try; increase the working
  434. // set size and try again.
  435. SIZE_T min_ws_size, max_ws_size;
  436. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  437. fprintf(stderr, "warning: GetProcessWorkingSetSize failed: %s\n",
  438. llama_format_win_err(GetLastError()).c_str());
  439. return false;
  440. }
  441. // Per MSDN: "The maximum number of pages that a process can lock
  442. // is equal to the number of pages in its minimum working set minus
  443. // a small overhead."
  444. // Hopefully a megabyte is enough overhead:
  445. size_t increment = len + 1048576;
  446. // The minimum must be <= the maximum, so we need to increase both:
  447. min_ws_size += increment;
  448. max_ws_size += increment;
  449. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  450. fprintf(stderr, "warning: SetProcessWorkingSetSize failed: %s\n",
  451. llama_format_win_err(GetLastError()).c_str());
  452. return false;
  453. }
  454. }
  455. }
  456. static void raw_unlock(void * ptr, size_t len) {
  457. if (!VirtualUnlock(ptr, len)) {
  458. fprintf(stderr, "warning: failed to VirtualUnlock buffer: %s\n",
  459. llama_format_win_err(GetLastError()).c_str());
  460. }
  461. }
  462. #else
  463. static constexpr bool SUPPORTED = false;
  464. static size_t lock_granularity() {
  465. return (size_t) 65536;
  466. }
  467. bool raw_lock(const void * addr, size_t len) const {
  468. fprintf(stderr, "warning: mlock not supported on this system\n");
  469. return false;
  470. }
  471. static void raw_unlock(const void * addr, size_t len) {}
  472. #endif
  473. };
  474. typedef void (*offload_func_t)(struct ggml_tensor * tensor);
  475. static void llama_nop(struct ggml_tensor * tensor) { // don't offload by default
  476. (void) tensor;
  477. }
  478. static std::string llama_token_to_text(const struct llama_context * ctx, llama_token token) {
  479. std::vector<char> result(8, 0);
  480. const int n_tokens = llama_token_to_str(ctx, token, result.data(), result.size());
  481. if (n_tokens < 0) {
  482. result.resize(-n_tokens);
  483. int check = llama_token_to_str(ctx, token, result.data(), result.size());
  484. GGML_ASSERT(check == -n_tokens);
  485. } else {
  486. result.resize(n_tokens);
  487. }
  488. return std::string(result.data(), result.size());
  489. }
  490. //
  491. // globals
  492. //
  493. struct llama_state {
  494. // We save the log callback globally
  495. llama_log_callback log_callback = llama_log_callback_default;
  496. void * log_callback_user_data = nullptr;
  497. };
  498. static llama_state g_state;
  499. // available llama models
  500. enum e_model {
  501. MODEL_UNKNOWN,
  502. MODEL_3B,
  503. MODEL_7B,
  504. MODEL_13B,
  505. MODEL_30B,
  506. MODEL_65B,
  507. MODEL_70B,
  508. };
  509. static const size_t kB = 1024;
  510. static const size_t MB = 1024*1024;
  511. // default hparams (LLaMA 7B)
  512. struct llama_hparams {
  513. uint32_t n_vocab = 32000;
  514. uint32_t n_ctx_train = 2048; // the context size used during training
  515. uint32_t n_ctx = 512; // the context size used during inference
  516. uint32_t n_embd = 4096;
  517. uint32_t n_head = 32;
  518. uint32_t n_head_kv = 32;
  519. uint32_t n_layer = 32;
  520. uint32_t n_rot = 64;
  521. uint32_t n_ff = 11008;
  522. float f_norm_rms_eps = 1e-5;
  523. float rope_freq_base = 10000.0f;
  524. float rope_freq_scale = 1.0f;
  525. bool operator!=(const llama_hparams & other) const {
  526. return static_cast<bool>(memcmp(this, &other, sizeof(llama_hparams))); // NOLINT
  527. }
  528. uint32_t n_gqa() const {
  529. return n_head/n_head_kv;
  530. }
  531. uint32_t n_embd_head() const {
  532. return n_embd/n_head;
  533. }
  534. uint32_t n_embd_gqa() const {
  535. return n_embd/n_gqa();
  536. }
  537. size_t kv_size() const {
  538. size_t result = 2ull;
  539. result *= (size_t) n_embd_gqa();
  540. result *= (size_t) n_ctx;
  541. result *= (size_t) n_layer;
  542. result *= sizeof(ggml_fp16_t);
  543. return result;
  544. }
  545. };
  546. struct llama_layer {
  547. // normalization
  548. struct ggml_tensor * attention_norm;
  549. // attention
  550. struct ggml_tensor * wq;
  551. struct ggml_tensor * wk;
  552. struct ggml_tensor * wv;
  553. struct ggml_tensor * wo;
  554. // normalization
  555. struct ggml_tensor * ffn_norm;
  556. // ff
  557. struct ggml_tensor * w1;
  558. struct ggml_tensor * w2;
  559. struct ggml_tensor * w3;
  560. };
  561. struct llama_kv_cache {
  562. struct ggml_tensor * k = NULL;
  563. struct ggml_tensor * v = NULL;
  564. struct ggml_context * ctx = NULL;
  565. llama_buffer buf;
  566. int n; // number of tokens currently in the cache
  567. ~llama_kv_cache() {
  568. if (ctx) {
  569. ggml_free(ctx);
  570. }
  571. #ifdef GGML_USE_CUBLAS
  572. ggml_cuda_free_data(k);
  573. ggml_cuda_free_data(v);
  574. #endif // GGML_USE_CUBLAS
  575. }
  576. };
  577. struct llama_vocab {
  578. // TODO:
  579. // - add a vector of merges
  580. // so that we can pass it to different types of tokenizers with a common interface
  581. using id = int32_t;
  582. using token = std::string;
  583. using ttype = llama_token_type;
  584. struct token_data {
  585. token text;
  586. float score;
  587. ttype type;
  588. };
  589. llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  590. std::unordered_map<token, id> token_to_id;
  591. std::vector<token_data> id_to_token;
  592. // default LLaMA special tokens
  593. id special_bos_id = 1;
  594. id special_eos_id = 2;
  595. id special_unk_id = -1;
  596. id special_sep_id = -1;
  597. id special_pad_id = -1;
  598. id linefeed_id = 13;
  599. };
  600. struct llama_model {
  601. e_model type = MODEL_UNKNOWN;
  602. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  603. llama_hparams hparams;
  604. llama_vocab vocab;
  605. struct ggml_tensor * tok_embeddings;
  606. struct ggml_tensor * norm;
  607. struct ggml_tensor * output;
  608. std::vector<llama_layer> layers;
  609. int n_gpu_layers;
  610. // context
  611. struct ggml_context * ctx = NULL;
  612. // the model memory buffer
  613. llama_buffer buf;
  614. // model memory mapped file
  615. std::unique_ptr<llama_mmap> mapping;
  616. // objects representing data potentially being locked in memory
  617. llama_mlock mlock_buf;
  618. llama_mlock mlock_mmap;
  619. // for quantize-stats only
  620. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  621. int64_t t_load_us = 0;
  622. int64_t t_start_us = 0;
  623. ~llama_model() {
  624. if (ctx) {
  625. ggml_free(ctx);
  626. }
  627. #ifdef GGML_USE_CUBLAS
  628. for (size_t i = 0; i < tensors_by_name.size(); ++i) {
  629. ggml_cuda_free_data(tensors_by_name[i].second);
  630. }
  631. ggml_cuda_free_scratch();
  632. #elif defined(GGML_USE_CLBLAST)
  633. for (size_t i = 0; i < tensors_by_name.size(); ++i) {
  634. ggml_cl_free_data(tensors_by_name[i].second);
  635. }
  636. #endif
  637. }
  638. };
  639. struct llama_context {
  640. llama_context(const llama_model & model) : model(model), t_load_us(model.t_load_us), t_start_us(model.t_start_us) {}
  641. ~llama_context() {
  642. if (model_owner) {
  643. delete &model;
  644. }
  645. #ifdef GGML_USE_METAL
  646. if (ctx_metal) {
  647. ggml_metal_free(ctx_metal);
  648. }
  649. #endif
  650. if (alloc) {
  651. ggml_allocr_free(alloc);
  652. }
  653. }
  654. std::mt19937 rng;
  655. bool has_evaluated_once = false;
  656. int64_t t_sample_us = 0;
  657. int64_t t_eval_us = 0;
  658. int64_t t_p_eval_us = 0;
  659. int32_t n_sample = 0; // number of tokens sampled
  660. int32_t n_eval = 0; // number of eval calls
  661. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  662. const llama_model & model;
  663. bool model_owner = false;
  664. int64_t t_load_us;
  665. int64_t t_start_us;
  666. // key + value cache for the self attention
  667. struct llama_kv_cache kv_self;
  668. size_t mem_per_token = 0;
  669. // decode output (2-dimensional array: [n_tokens][n_vocab])
  670. std::vector<float> logits;
  671. bool logits_all = false;
  672. // input embedding (1-dimensional array: [n_embd])
  673. std::vector<float> embedding;
  674. // reusable buffer for `struct ggml_graph_plan.work_data`
  675. std::vector<uint8_t> work_buffer;
  676. // memory buffers used to evaluate the model
  677. llama_buffer buf_compute;
  678. llama_buffer buf_alloc;
  679. ggml_allocr * alloc = NULL;
  680. #ifdef GGML_USE_METAL
  681. ggml_metal_context * ctx_metal = NULL;
  682. #endif
  683. #ifdef GGML_USE_MPI
  684. ggml_mpi_context * ctx_mpi = NULL;
  685. #endif
  686. };
  687. //
  688. // kv cache helpers
  689. //
  690. static bool llama_kv_cache_init(
  691. const struct llama_hparams & hparams,
  692. struct llama_kv_cache & cache,
  693. ggml_type wtype,
  694. int n_ctx,
  695. int n_gpu_layers) {
  696. const int n_embd = hparams.n_embd_gqa();
  697. const int n_layer = hparams.n_layer;
  698. const int64_t n_mem = n_layer*n_ctx;
  699. const int64_t n_elements = n_embd*n_mem;
  700. cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
  701. cache.n = 0;
  702. struct ggml_init_params params;
  703. params.mem_size = cache.buf.size;
  704. params.mem_buffer = cache.buf.data;
  705. params.no_alloc = false;
  706. cache.ctx = ggml_init(params);
  707. if (!cache.ctx) {
  708. LLAMA_LOG_ERROR("%s: failed to allocate memory for kv cache\n", __func__);
  709. return false;
  710. }
  711. cache.k = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  712. cache.v = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  713. ggml_set_name(cache.k, "cache_k");
  714. ggml_set_name(cache.v, "cache_v");
  715. (void) n_gpu_layers;
  716. #ifdef GGML_USE_CUBLAS
  717. if (n_gpu_layers > n_layer + 1) {
  718. ggml_cuda_assign_buffers_no_scratch(cache.v);
  719. }
  720. if (n_gpu_layers > n_layer + 2) {
  721. ggml_cuda_assign_buffers_no_scratch(cache.k);
  722. }
  723. #endif // GGML_USE_CUBLAS
  724. return true;
  725. }
  726. //
  727. // model loading and saving
  728. //
  729. enum llama_file_version {
  730. GGUF_FILE_VERSION_V1 = 1,
  731. };
  732. static const char * llama_file_version_name(llama_file_version version) {
  733. switch (version) {
  734. case GGUF_FILE_VERSION_V1: return "GGUF V1 (latest)";
  735. }
  736. return "unknown";
  737. }
  738. static std::string llama_format_tensor_shape(const std::vector<uint32_t> & ne) {
  739. char buf[256];
  740. snprintf(buf, sizeof(buf), "%5u", ne.at(0));
  741. for (size_t i = 1; i < ne.size(); i++) {
  742. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5u", ne.at(i));
  743. }
  744. return buf;
  745. }
  746. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  747. char buf[256];
  748. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  749. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  750. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  751. }
  752. return buf;
  753. }
  754. struct llama_model_loader {
  755. int n_kv = 0;
  756. int n_tensors = 0;
  757. int n_created = 0;
  758. int64_t n_elements = 0;
  759. bool use_mmap = false;
  760. llama_file file;
  761. llama_ftype ftype;
  762. llama_file_version fver;
  763. std::unique_ptr<llama_mmap> mapping;
  764. struct gguf_context * ctx_gguf = NULL;
  765. struct ggml_context * ctx_meta = NULL;
  766. llama_model_loader(const std::string & fname, bool use_mmap) : file(fname.c_str(), "rb") {
  767. struct gguf_init_params params = {
  768. /*.no_alloc = */ true,
  769. /*.ctx = */ &ctx_meta,
  770. };
  771. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  772. if (!ctx_gguf) {
  773. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  774. }
  775. n_kv = gguf_get_n_kv(ctx_gguf);
  776. n_tensors = gguf_get_n_tensors(ctx_gguf);
  777. fver = (enum llama_file_version) gguf_get_version(ctx_gguf);
  778. for (int i = 0; i < n_tensors; i++) {
  779. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  780. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  781. n_elements += ggml_nelements(t);
  782. }
  783. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  784. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  785. // determine file type based on the number of tensors for each quantization and print meta data
  786. // TODO: make optional
  787. {
  788. std::map<enum ggml_type, uint32_t> n_type;
  789. uint32_t n_type_max = 0;
  790. enum ggml_type type_max = GGML_TYPE_F32;
  791. for (int i = 0; i < n_tensors; i++) {
  792. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  793. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, name);
  794. n_type[meta->type]++;
  795. if (n_type_max < n_type[meta->type]) {
  796. n_type_max = n_type[meta->type];
  797. type_max = meta->type;
  798. }
  799. 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());
  800. }
  801. switch (type_max) {
  802. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  803. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  804. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  805. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  806. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  807. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  808. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  809. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  810. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  811. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  812. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  813. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  814. default:
  815. {
  816. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  817. ftype = LLAMA_FTYPE_ALL_F32;
  818. } break;
  819. }
  820. for (int i = 0; i < n_kv; i++) {
  821. const char * name = gguf_get_key(ctx_gguf, i);
  822. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  823. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-8s\n", __func__, i, name, gguf_type_name(type));
  824. }
  825. // print type counts
  826. for (auto & kv : n_type) {
  827. if (kv.second == 0) {
  828. continue;
  829. }
  830. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  831. }
  832. }
  833. if (!llama_mmap::SUPPORTED) {
  834. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  835. use_mmap = false;
  836. }
  837. this->use_mmap = use_mmap;
  838. }
  839. ~llama_model_loader() {
  840. if (ctx_gguf) {
  841. gguf_free(ctx_gguf);
  842. }
  843. if (ctx_meta) {
  844. ggml_free(ctx_meta);
  845. }
  846. }
  847. const char * get_tensor_name(int i) const {
  848. return gguf_get_tensor_name(ctx_gguf, i);
  849. }
  850. struct ggml_tensor * get_tensor_meta(int i) const {
  851. return ggml_get_tensor(ctx_meta, get_tensor_name(i));
  852. }
  853. void calc_sizes(size_t & ctx_size_p, size_t & mmapped_size_p) const {
  854. ctx_size_p = 0;
  855. mmapped_size_p = 0;
  856. for (int i = 0; i < n_tensors; i++) {
  857. struct ggml_tensor * meta = get_tensor_meta(i);
  858. ctx_size_p += sizeof(struct ggml_tensor) + GGML_OBJECT_SIZE;
  859. (use_mmap ? mmapped_size_p : ctx_size_p) += ggml_nbytes_pad(meta);
  860. }
  861. }
  862. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta, ggml_backend backend) {
  863. if (backend != GGML_BACKEND_CPU) {
  864. ggml_set_no_alloc(ctx, true);
  865. }
  866. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  867. tensor->backend = backend; // TODO: ggml_set_backend
  868. ggml_set_name(tensor, ggml_get_name(meta));
  869. if (backend != GGML_BACKEND_CPU) {
  870. ggml_set_no_alloc(ctx, use_mmap);
  871. }
  872. n_created++;
  873. return tensor;
  874. }
  875. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<uint32_t> & ne, ggml_backend backend) {
  876. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  877. if (cur == NULL) {
  878. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  879. }
  880. {
  881. bool is_ok = true;
  882. for (size_t i = 0; i < ne.size(); ++i) {
  883. if (ne[i] != cur->ne[i]) {
  884. is_ok = false;
  885. break;
  886. }
  887. }
  888. if (!is_ok) {
  889. throw std::runtime_error(
  890. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  891. __func__, name.c_str(),
  892. llama_format_tensor_shape(ne).c_str(),
  893. llama_format_tensor_shape(cur).c_str()));
  894. }
  895. }
  896. return create_tensor_for(ctx, cur, backend);
  897. }
  898. void done_getting_tensors() const {
  899. if (n_created != n_tensors) {
  900. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  901. }
  902. }
  903. size_t file_offset(const char * name) const {
  904. const int idx = gguf_find_tensor(ctx_gguf, name);
  905. if (idx < 0) {
  906. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  907. }
  908. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  909. }
  910. void load_data_for(struct ggml_tensor * cur) const {
  911. const size_t offs = file_offset(ggml_get_name(cur));
  912. if (use_mmap) {
  913. cur->data = (uint8_t *) mapping->addr + offs;
  914. } else {
  915. file.seek(offs, SEEK_SET);
  916. file.read_raw(cur->data, ggml_nbytes(cur));
  917. }
  918. }
  919. void load_all_data(struct ggml_context * ctx, llama_progress_callback progress_callback, void * progress_callback_user_data, llama_mlock * lmlock) {
  920. size_t size_data = 0;
  921. size_t size_lock = 0;
  922. size_t size_pref = 0; // prefetch
  923. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  924. struct ggml_tensor * cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
  925. size_data += ggml_nbytes(cur);
  926. if (cur->backend == GGML_BACKEND_CPU) {
  927. size_pref += ggml_nbytes(cur);
  928. }
  929. }
  930. if (use_mmap) {
  931. mapping.reset(new llama_mmap(&file, size_pref, ggml_is_numa()));
  932. if (lmlock) {
  933. lmlock->init(mapping->addr);
  934. }
  935. }
  936. size_t done_size = 0;
  937. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  938. struct ggml_tensor * cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
  939. GGML_ASSERT(cur); // unused tensors should have been caught by load_data already
  940. if (progress_callback) {
  941. progress_callback((float) done_size / size_data, progress_callback_user_data);
  942. }
  943. // allocate temp buffer if not using mmap
  944. if (!use_mmap && cur->data == NULL) {
  945. GGML_ASSERT(cur->backend != GGML_BACKEND_CPU);
  946. cur->data = malloc(ggml_nbytes(cur));
  947. }
  948. load_data_for(cur);
  949. switch (cur->backend) {
  950. case GGML_BACKEND_CPU:
  951. if (use_mmap && lmlock) {
  952. size_lock += ggml_nbytes(cur);
  953. lmlock->grow_to(size_lock);
  954. }
  955. break;
  956. #if defined(GGML_USE_CUBLAS)
  957. case GGML_BACKEND_GPU:
  958. case GGML_BACKEND_GPU_SPLIT:
  959. // old code:
  960. //ggml_cuda_transform_tensor(lt.data, lt.ggml_tensor);
  961. // TODO: test if this works !!
  962. ggml_cuda_transform_tensor(cur->data, cur);
  963. if (!use_mmap) {
  964. free(cur->data);
  965. }
  966. break;
  967. #elif defined(GGML_USE_CLBLAST)
  968. case GGML_BACKEND_GPU:
  969. ggml_cl_transform_tensor(cur->data, cur);
  970. if (!use_mmap) {
  971. free(cur->data);
  972. }
  973. break;
  974. #endif
  975. default:
  976. continue;
  977. }
  978. done_size += ggml_nbytes(cur);
  979. }
  980. }
  981. };
  982. //
  983. // load LLaMA models
  984. //
  985. const char * llama_model_ftype_name(enum llama_ftype ftype) {
  986. switch (ftype) {
  987. case LLAMA_FTYPE_ALL_F32: return "all F32";
  988. case LLAMA_FTYPE_MOSTLY_F16: return "mostly F16";
  989. case LLAMA_FTYPE_MOSTLY_Q4_0: return "mostly Q4_0";
  990. case LLAMA_FTYPE_MOSTLY_Q4_1: return "mostly Q4_1";
  991. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  992. return "mostly Q4_1, some F16";
  993. case LLAMA_FTYPE_MOSTLY_Q5_0: return "mostly Q5_0";
  994. case LLAMA_FTYPE_MOSTLY_Q5_1: return "mostly Q5_1";
  995. case LLAMA_FTYPE_MOSTLY_Q8_0: return "mostly Q8_0";
  996. // K-quants
  997. case LLAMA_FTYPE_MOSTLY_Q2_K: return "mostly Q2_K";
  998. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "mostly Q3_K - Small";
  999. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "mostly Q3_K - Medium";
  1000. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "mostly Q3_K - Large";
  1001. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "mostly Q4_K - Small";
  1002. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "mostly Q4_K - Medium";
  1003. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "mostly Q5_K - Small";
  1004. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "mostly Q5_K - Medium";
  1005. case LLAMA_FTYPE_MOSTLY_Q6_K: return "mostly Q6_K";
  1006. default: return "unknown, may not work";
  1007. }
  1008. }
  1009. static const char * llama_model_type_name(e_model type) {
  1010. switch (type) {
  1011. case MODEL_3B: return "3B";
  1012. case MODEL_7B: return "7B";
  1013. case MODEL_13B: return "13B";
  1014. case MODEL_30B: return "30B";
  1015. case MODEL_65B: return "65B";
  1016. case MODEL_70B: return "70B";
  1017. default: GGML_ASSERT(false);
  1018. }
  1019. }
  1020. static void llama_model_load_internal(
  1021. const std::string & fname,
  1022. llama_model & model,
  1023. llama_vocab & vocab,
  1024. int n_ctx,
  1025. int n_batch,
  1026. int n_gpu_layers,
  1027. int main_gpu,
  1028. const float * tensor_split,
  1029. const bool mul_mat_q,
  1030. float rope_freq_base,
  1031. float rope_freq_scale,
  1032. bool low_vram,
  1033. ggml_type memory_type,
  1034. bool use_mmap,
  1035. bool use_mlock,
  1036. bool vocab_only,
  1037. llama_progress_callback progress_callback,
  1038. void * progress_callback_user_data) {
  1039. model.t_start_us = ggml_time_us();
  1040. std::unique_ptr<llama_model_loader> ml(new llama_model_loader(fname, use_mmap));
  1041. model.n_gpu_layers = n_gpu_layers;
  1042. auto & hparams = model.hparams;
  1043. std::string general_name = "n/a";
  1044. std::string general_arch = "n/a";
  1045. // read hparams
  1046. {
  1047. struct gguf_context * ctx = ml->ctx_gguf;
  1048. #define GGUF_GET(dst, func, type, req, key) \
  1049. { \
  1050. const int kid = gguf_find_key(ctx, key); \
  1051. if (kid >= 0) { \
  1052. enum gguf_type ktype = gguf_get_kv_type(ctx, kid); \
  1053. if (ktype != (type)) { \
  1054. throw std::runtime_error(format("key %s has wrong type: %s", key, gguf_type_name(ktype))); \
  1055. } \
  1056. (dst) = func(ctx, kid); \
  1057. } else if (req) { \
  1058. throw std::runtime_error(format("key not found in model: %s", key)); \
  1059. } \
  1060. }
  1061. std::string tokenizer_name;
  1062. GGUF_GET(tokenizer_name, gguf_get_val_str, GGUF_TYPE_STRING, true, "tokenizer.ggml.model");
  1063. if (tokenizer_name == "llama") {
  1064. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  1065. } else if (tokenizer_name == "gpt2") {
  1066. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  1067. } else {
  1068. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  1069. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  1070. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  1071. }
  1072. // get hparams kv
  1073. GGUF_GET(hparams.n_vocab, gguf_get_arr_n, GGUF_TYPE_ARRAY, true, "tokenizer.ggml.tokens");
  1074. GGUF_GET(hparams.n_ctx_train, gguf_get_val_u32, GGUF_TYPE_UINT32, true, "llama.context_length");
  1075. GGUF_GET(hparams.n_embd, gguf_get_val_u32, GGUF_TYPE_UINT32, true, "llama.embedding_length");
  1076. GGUF_GET(hparams.n_ff, gguf_get_val_u32, GGUF_TYPE_UINT32, true, "llama.feed_forward_length");
  1077. GGUF_GET(hparams.n_head, gguf_get_val_u32, GGUF_TYPE_UINT32, true, "llama.attention.head_count");
  1078. GGUF_GET(hparams.n_layer, gguf_get_val_u32, GGUF_TYPE_UINT32, true, "llama.block_count");
  1079. GGUF_GET(hparams.n_rot, gguf_get_val_u32, GGUF_TYPE_UINT32, true, "llama.rope.dimension_count");
  1080. GGUF_GET(hparams.f_norm_rms_eps, gguf_get_val_f32, GGUF_TYPE_FLOAT32, true, "llama.attention.layer_norm_rms_epsilon");
  1081. // n_head_kv is optional, default to n_head
  1082. hparams.n_head_kv = hparams.n_head;
  1083. GGUF_GET(hparams.n_head_kv, gguf_get_val_u32, GGUF_TYPE_UINT32, false, "llama.attention.head_count_kv");
  1084. // TODO: manually setting rope scale should override this
  1085. // rope_freq_scale (inverse of the kv) is optional
  1086. float ropescale = 1.0f;
  1087. GGUF_GET(ropescale, gguf_get_val_f32, GGUF_TYPE_FLOAT32, false, "llama.rope.scale_linear");
  1088. if (ropescale != 1.0f) {
  1089. rope_freq_scale = 1.0f/ropescale;
  1090. }
  1091. // get general kv
  1092. GGUF_GET(general_name, gguf_get_val_str, GGUF_TYPE_STRING, false, "general.name");
  1093. GGUF_GET(general_arch, gguf_get_val_str, GGUF_TYPE_STRING, false, "general.architecture");
  1094. // special tokens
  1095. GGUF_GET(vocab.special_bos_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, "tokenizer.ggml.bos_token_id");
  1096. GGUF_GET(vocab.special_eos_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, "tokenizer.ggml.eos_token_id");
  1097. GGUF_GET(vocab.special_unk_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, "tokenizer.ggml.unknown_token_id");
  1098. GGUF_GET(vocab.special_sep_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, "tokenizer.ggml.separator_token_id");
  1099. GGUF_GET(vocab.special_pad_id, gguf_get_val_u32, GGUF_TYPE_UINT32, false, "tokenizer.ggml.padding_token_id");
  1100. #undef GGUF_GET
  1101. switch (hparams.n_layer) {
  1102. case 26: model.type = e_model::MODEL_3B; break;
  1103. case 32: model.type = e_model::MODEL_7B; break;
  1104. case 40: model.type = e_model::MODEL_13B; break;
  1105. case 60: model.type = e_model::MODEL_30B; break;
  1106. case 80: model.type = e_model::MODEL_65B; break;
  1107. default:
  1108. {
  1109. if (hparams.n_layer < 32) {
  1110. model.type = e_model::MODEL_7B;
  1111. }
  1112. } break;
  1113. }
  1114. model.ftype = ml->ftype;
  1115. hparams.n_ctx = n_ctx;
  1116. // LLaMAv2
  1117. // TODO: probably not needed
  1118. {
  1119. const auto n_gqa = hparams.n_gqa();
  1120. if (model.type == e_model::MODEL_65B && n_gqa == 8) {
  1121. LLAMA_LOG_WARN("%s: assuming 70B model based on GQA == %d\n", __func__, n_gqa);
  1122. model.type = e_model::MODEL_70B;
  1123. }
  1124. }
  1125. hparams.rope_freq_base = rope_freq_base;
  1126. hparams.rope_freq_scale = rope_freq_scale;
  1127. }
  1128. // read vocab
  1129. {
  1130. struct gguf_context * ctx = ml->ctx_gguf;
  1131. vocab.id_to_token.resize(hparams.n_vocab);
  1132. const int token_idx = gguf_find_key(ctx, "tokenizer.ggml.tokens");
  1133. if (token_idx == -1) {
  1134. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  1135. }
  1136. const int score_idx = gguf_find_key(ctx, "tokenizer.ggml.scores");
  1137. if (score_idx == -1) {
  1138. throw std::runtime_error("cannot find tokenizer scores in model file\n");
  1139. }
  1140. const float * scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  1141. const int toktype_idx = gguf_find_key(ctx, "tokenizer.ggml.token_type");
  1142. if (toktype_idx == -1) {
  1143. throw std::runtime_error("cannot find token type list in GGUF file\n");
  1144. }
  1145. const int * toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  1146. for (uint32_t i = 0; i < hparams.n_vocab; i++) {
  1147. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  1148. vocab.token_to_id[word] = i;
  1149. auto & token_data = vocab.id_to_token[i];
  1150. token_data.text = std::move(word);
  1151. token_data.score = scores[i];
  1152. token_data.type = (llama_token_type) toktypes[i];
  1153. // determine the newline token: 0x0A == 10 == '\n'
  1154. if (token_data.text == "<0x0A>") {
  1155. vocab.linefeed_id = i;
  1156. }
  1157. }
  1158. }
  1159. {
  1160. // hparams
  1161. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml->fver));
  1162. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, general_arch.c_str());
  1163. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, vocab.type == LLAMA_VOCAB_TYPE_SPM ? "SPM" : "BPE"); // TODO: fix
  1164. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  1165. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  1166. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, hparams.n_ctx);
  1167. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  1168. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  1169. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  1170. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  1171. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot); // a.k.a. n_embd_head, n_head_dim
  1172. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  1173. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  1174. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  1175. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, hparams.rope_freq_base);
  1176. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, hparams.rope_freq_scale);
  1177. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  1178. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype));
  1179. LLAMA_LOG_INFO("%s: model size = %.2f B\n", __func__, ml->n_elements*1e-9);
  1180. // general kv
  1181. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, general_name.c_str());
  1182. // special tokens
  1183. 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() ); }
  1184. 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() ); }
  1185. 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() ); }
  1186. 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() ); }
  1187. 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() ); }
  1188. 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() ); }
  1189. }
  1190. if (vocab_only) {
  1191. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  1192. return;
  1193. }
  1194. auto & ctx = model.ctx;
  1195. size_t ctx_size;
  1196. size_t mmapped_size;
  1197. ml->calc_sizes(ctx_size, mmapped_size);
  1198. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MB\n", __func__, ctx_size/1024.0/1024.0);
  1199. // create the ggml context
  1200. {
  1201. model.buf.resize(ctx_size);
  1202. if (use_mlock) {
  1203. model.mlock_buf.init (model.buf.data);
  1204. model.mlock_buf.grow_to(model.buf.size);
  1205. }
  1206. struct ggml_init_params params = {
  1207. /*.mem_size =*/ model.buf.size,
  1208. /*.mem_buffer =*/ model.buf.data,
  1209. /*.no_alloc =*/ ml->use_mmap,
  1210. };
  1211. model.ctx = ggml_init(params);
  1212. if (!model.ctx) {
  1213. throw std::runtime_error(format("ggml_init() failed"));
  1214. }
  1215. }
  1216. (void) main_gpu;
  1217. (void) mul_mat_q;
  1218. #if defined(GGML_USE_CUBLAS)
  1219. LLAMA_LOG_INFO("%s: using CUDA for GPU acceleration\n", __func__);
  1220. ggml_cuda_set_main_device(main_gpu);
  1221. ggml_cuda_set_mul_mat_q(mul_mat_q);
  1222. #define LLAMA_BACKEND_OFFLOAD GGML_BACKEND_GPU
  1223. #define LLAMA_BACKEND_OFFLOAD_SPLIT GGML_BACKEND_GPU_SPLIT
  1224. #elif defined(GGML_USE_CLBLAST)
  1225. LLAMA_LOG_INFO("%s: using OpenCL for GPU acceleration\n", __func__);
  1226. #define LLAMA_BACKEND_OFFLOAD GGML_BACKEND_GPU
  1227. #define LLAMA_BACKEND_OFFLOAD_SPLIT GGML_BACKEND_GPU
  1228. #else
  1229. #define LLAMA_BACKEND_OFFLOAD GGML_BACKEND_CPU
  1230. #define LLAMA_BACKEND_OFFLOAD_SPLIT GGML_BACKEND_CPU
  1231. #endif
  1232. // prepare memory for the weights
  1233. size_t vram_weights = 0;
  1234. {
  1235. const uint32_t n_embd = hparams.n_embd;
  1236. const uint32_t n_embd_gqa = hparams.n_embd_gqa();
  1237. const uint32_t n_layer = hparams.n_layer;
  1238. const uint32_t n_vocab = hparams.n_vocab;
  1239. model.tok_embeddings = ml->create_tensor(ctx, TN_TOKEN_EMBD, {n_embd, n_vocab}, GGML_BACKEND_CPU);
  1240. // "output" tensor
  1241. {
  1242. ggml_backend backend_norm;
  1243. ggml_backend backend_output;
  1244. if (n_gpu_layers > int(n_layer)) { // NOLINT
  1245. // norm is not performance relevant on its own but keeping it in VRAM reduces data copying
  1246. // on Windows however this is detrimental unless everything is on the GPU
  1247. #ifndef _WIN32
  1248. backend_norm = low_vram ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  1249. #else
  1250. backend_norm = low_vram || n_gpu_layers <= (int) n_layer + 2 ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  1251. #endif // _WIN32
  1252. backend_output = LLAMA_BACKEND_OFFLOAD_SPLIT;
  1253. } else {
  1254. backend_norm = GGML_BACKEND_CPU;
  1255. backend_output = GGML_BACKEND_CPU;
  1256. }
  1257. model.norm = ml->create_tensor(ctx, TN_OUTPUT_NORM, {n_embd}, backend_norm);
  1258. model.output = ml->create_tensor(ctx, TN_OUTPUT, {n_embd, n_vocab}, backend_output);
  1259. if (backend_norm == GGML_BACKEND_GPU) {
  1260. vram_weights += ggml_nbytes(model.norm);
  1261. }
  1262. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  1263. vram_weights += ggml_nbytes(model.output);
  1264. }
  1265. }
  1266. const uint32_t n_ff = hparams.n_ff;
  1267. const int i_gpu_start = n_layer - n_gpu_layers;
  1268. model.layers.resize(n_layer);
  1269. for (uint32_t i = 0; i < n_layer; ++i) {
  1270. const ggml_backend backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD; // NOLINT
  1271. const ggml_backend backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD_SPLIT; // NOLINT
  1272. auto & layer = model.layers[i];
  1273. layer.attention_norm = ml->create_tensor(ctx, format(TN_ATTN_NORM, i), {n_embd}, backend);
  1274. layer.wq = ml->create_tensor(ctx, format(TN_ATTN_Q, i), {n_embd, n_embd}, backend_split);
  1275. layer.wk = ml->create_tensor(ctx, format(TN_ATTN_K, i), {n_embd, n_embd_gqa}, backend_split);
  1276. layer.wv = ml->create_tensor(ctx, format(TN_ATTN_V, i), {n_embd, n_embd_gqa}, backend_split);
  1277. layer.wo = ml->create_tensor(ctx, format(TN_ATTN_OUTPUT, i), {n_embd, n_embd}, backend_split);
  1278. layer.ffn_norm = ml->create_tensor(ctx, format(TN_FFN_NORM, i), {n_embd}, backend);
  1279. layer.w1 = ml->create_tensor(ctx, format(TN_FFN_GATE, i), {n_embd, n_ff}, backend_split);
  1280. layer.w2 = ml->create_tensor(ctx, format(TN_FFN_DOWN, i), { n_ff, n_embd}, backend_split);
  1281. layer.w3 = ml->create_tensor(ctx, format(TN_FFN_UP, i), {n_embd, n_ff}, backend_split);
  1282. if (backend == GGML_BACKEND_GPU) {
  1283. vram_weights +=
  1284. ggml_nbytes(layer.attention_norm) + ggml_nbytes(layer.wq) + ggml_nbytes(layer.wk) +
  1285. ggml_nbytes(layer.wv) + ggml_nbytes(layer.wo) + ggml_nbytes(layer.ffn_norm) +
  1286. ggml_nbytes(layer.w1) + ggml_nbytes(layer.w2) + ggml_nbytes(layer.w3);
  1287. }
  1288. }
  1289. }
  1290. ml->done_getting_tensors();
  1291. // print memory requirements
  1292. {
  1293. const size_t scale = memory_type == GGML_TYPE_F32 ? 2 : 1;
  1294. // this is the total memory required to run the inference
  1295. size_t mem_required =
  1296. ctx_size +
  1297. mmapped_size - vram_weights; // weights in VRAM not in memory
  1298. // this is the memory required by one llama_state
  1299. const size_t mem_required_state =
  1300. scale*hparams.kv_size();
  1301. LLAMA_LOG_INFO("%s: mem required = %7.2f MB (+ %7.2f MB per state)\n", __func__,
  1302. mem_required / 1024.0 / 1024.0, mem_required_state / 1024.0 / 1024.0);
  1303. (void) n_batch;
  1304. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST)
  1305. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  1306. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  1307. if (n_gpu_layers > (int) hparams.n_layer) {
  1308. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  1309. }
  1310. size_t vram_kv_cache = 0;
  1311. #ifdef GGML_USE_CUBLAS
  1312. const int max_backend_supported_layers = hparams.n_layer + 3;
  1313. const int max_offloadable_layers = low_vram ? hparams.n_layer + 1 : hparams.n_layer + 3;
  1314. if (n_gpu_layers > (int) hparams.n_layer + 1) {
  1315. if (low_vram) {
  1316. LLAMA_LOG_INFO("%s: cannot offload v cache to GPU due to low VRAM option\n", __func__);
  1317. } else {
  1318. LLAMA_LOG_INFO("%s: offloading v cache to GPU\n", __func__);
  1319. vram_kv_cache += hparams.kv_size() / 2;
  1320. }
  1321. }
  1322. if (n_gpu_layers > (int) hparams.n_layer + 2) {
  1323. if (low_vram) {
  1324. LLAMA_LOG_WARN("%s: cannot offload k cache to GPU due to low VRAM option\n", __func__);
  1325. } else {
  1326. LLAMA_LOG_INFO("%s: offloading k cache to GPU\n", __func__);
  1327. vram_kv_cache += hparams.kv_size() / 2;
  1328. }
  1329. }
  1330. #elif defined(GGML_USE_CLBLAST)
  1331. const int max_backend_supported_layers = hparams.n_layer + 1;
  1332. const int max_offloadable_layers = hparams.n_layer + 1;
  1333. #endif // GGML_USE_CUBLAS
  1334. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n",
  1335. __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  1336. LLAMA_LOG_INFO("%s: VRAM used: %zu MB\n",
  1337. __func__, (vram_weights + vram_kv_cache + MB - 1) / MB); // round up
  1338. #else
  1339. (void) n_gpu_layers;
  1340. #endif // defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST)
  1341. }
  1342. // populate `tensors_by_name`
  1343. for (int i = 0; i < ml->n_tensors; ++i) {
  1344. struct ggml_tensor * cur = ggml_get_tensor(ctx, ml->get_tensor_name(i));
  1345. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  1346. }
  1347. (void) tensor_split;
  1348. #if defined(GGML_USE_CUBLAS)
  1349. {
  1350. ggml_cuda_set_tensor_split(tensor_split);
  1351. }
  1352. #endif
  1353. ml->load_all_data(ctx, progress_callback, progress_callback_user_data, use_mlock ? &model.mlock_mmap : NULL);
  1354. if (progress_callback) {
  1355. progress_callback(1.0f, progress_callback_user_data);
  1356. }
  1357. model.mapping = std::move(ml->mapping);
  1358. // loading time will be recalculate after the first eval, so
  1359. // we take page faults deferred by mmap() into consideration
  1360. model.t_load_us = ggml_time_us() - model.t_start_us;
  1361. }
  1362. static bool llama_model_load(
  1363. const std::string & fname,
  1364. llama_model & model,
  1365. llama_vocab & vocab,
  1366. int n_ctx,
  1367. int n_batch,
  1368. int n_gpu_layers,
  1369. int main_gpu,
  1370. const float * tensor_split,
  1371. const bool mul_mat_q,
  1372. float rope_freq_base,
  1373. float rope_freq_scale,
  1374. bool low_vram,
  1375. ggml_type memory_type,
  1376. bool use_mmap,
  1377. bool use_mlock,
  1378. bool vocab_only,
  1379. llama_progress_callback progress_callback,
  1380. void *progress_callback_user_data) {
  1381. try {
  1382. llama_model_load_internal(fname, model, vocab, n_ctx, n_batch, n_gpu_layers,
  1383. main_gpu, tensor_split, mul_mat_q, rope_freq_base, rope_freq_scale, low_vram, memory_type,
  1384. use_mmap, use_mlock, vocab_only, progress_callback, progress_callback_user_data);
  1385. return true;
  1386. } catch (const std::exception & err) {
  1387. LLAMA_LOG_ERROR("error loading model: %s\n", err.what());
  1388. return false;
  1389. }
  1390. }
  1391. static struct ggml_cgraph * llama_build_graph(
  1392. llama_context & lctx,
  1393. const llama_token * tokens,
  1394. const float * embd,
  1395. int n_tokens,
  1396. int n_past) {
  1397. GGML_ASSERT((!tokens && embd) || (tokens && !embd)); // NOLINT
  1398. const int N = n_tokens;
  1399. const auto & model = lctx.model;
  1400. const auto & hparams = model.hparams;
  1401. const auto & kv_self = lctx.kv_self;
  1402. GGML_ASSERT(!!kv_self.ctx);
  1403. const int64_t n_embd = hparams.n_embd;
  1404. const int64_t n_layer = hparams.n_layer;
  1405. const int64_t n_ctx = hparams.n_ctx;
  1406. const int64_t n_head = hparams.n_head;
  1407. const int64_t n_head_kv = hparams.n_head_kv;
  1408. const int64_t n_embd_head = hparams.n_embd_head();
  1409. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  1410. GGML_ASSERT(n_embd_head == hparams.n_rot);
  1411. const float freq_base = hparams.rope_freq_base;
  1412. const float freq_scale = hparams.rope_freq_scale;
  1413. const float norm_rms_eps = hparams.f_norm_rms_eps;
  1414. const int n_gpu_layers = model.n_gpu_layers;
  1415. auto & mem_per_token = lctx.mem_per_token;
  1416. auto & buf_compute = lctx.buf_compute;
  1417. struct ggml_init_params params = {
  1418. /*.mem_size =*/ buf_compute.size,
  1419. /*.mem_buffer =*/ buf_compute.data,
  1420. /*.no_alloc =*/ false,
  1421. };
  1422. params.no_alloc = true;
  1423. struct ggml_context * ctx0 = ggml_init(params);
  1424. ggml_cgraph * gf = ggml_new_graph(ctx0);
  1425. struct ggml_tensor * cur;
  1426. struct ggml_tensor * inpL;
  1427. if (tokens) {
  1428. struct ggml_tensor * inp_tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  1429. ggml_allocr_alloc(lctx.alloc, inp_tokens);
  1430. if (!ggml_allocr_is_measure(lctx.alloc)) {
  1431. memcpy(inp_tokens->data, tokens, N*ggml_element_size(inp_tokens));
  1432. }
  1433. ggml_set_name(inp_tokens, "inp_tokens");
  1434. inpL = ggml_get_rows(ctx0, model.tok_embeddings, inp_tokens);
  1435. } else {
  1436. #ifdef GGML_USE_MPI
  1437. GGML_ASSERT(false && "not implemented");
  1438. #endif
  1439. inpL = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N);
  1440. ggml_allocr_alloc(lctx.alloc, inpL);
  1441. if (!ggml_allocr_is_measure(lctx.alloc)) {
  1442. memcpy(inpL->data, embd, N * n_embd * ggml_element_size(inpL));
  1443. }
  1444. }
  1445. const int i_gpu_start = n_layer - n_gpu_layers;
  1446. (void) i_gpu_start;
  1447. // offload functions set the tensor output backend to GPU
  1448. // tensors are GPU-accelerated if any input or the output has been offloaded
  1449. //
  1450. // with the low VRAM option VRAM scratch is disabled in llama_load_model_internal
  1451. // in that case ggml_cuda_assign_buffers has no effect
  1452. offload_func_t offload_func_nr = llama_nop; // nr = non-repeating
  1453. offload_func_t offload_func_kq = llama_nop;
  1454. offload_func_t offload_func_v = llama_nop;
  1455. #ifdef GGML_USE_CUBLAS
  1456. if (n_gpu_layers > n_layer) {
  1457. offload_func_nr = ggml_cuda_assign_buffers_no_alloc;
  1458. }
  1459. if (n_gpu_layers > n_layer + 1) {
  1460. offload_func_v = ggml_cuda_assign_buffers_no_alloc;
  1461. }
  1462. if (n_gpu_layers > n_layer + 2) {
  1463. offload_func_kq = ggml_cuda_assign_buffers_no_alloc;
  1464. }
  1465. #endif // GGML_USE_CUBLAS
  1466. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  1467. ggml_allocr_alloc(lctx.alloc, KQ_scale);
  1468. if (!ggml_allocr_is_measure(lctx.alloc)) {
  1469. ggml_set_f32(KQ_scale, 1.0f/sqrtf(float(n_embd)/n_head));
  1470. }
  1471. ggml_set_name(KQ_scale, "1/sqrt(n_embd_head)");
  1472. for (int il = 0; il < n_layer; ++il) {
  1473. ggml_format_name(inpL, "layer_inp_%d", il);
  1474. offload_func_t offload_func = llama_nop;
  1475. #ifdef GGML_USE_CUBLAS
  1476. if (il >= i_gpu_start) {
  1477. offload_func = ggml_cuda_assign_buffers_no_alloc;
  1478. }
  1479. #endif // GGML_USE_CUBLAS
  1480. struct ggml_tensor * inpSA = inpL;
  1481. // norm
  1482. {
  1483. cur = ggml_rms_norm(ctx0, inpL, norm_rms_eps);
  1484. offload_func(cur);
  1485. ggml_set_name(cur, "rms_norm_0");
  1486. // cur = cur*attention_norm(broadcasted)
  1487. cur = ggml_mul(ctx0, cur, model.layers[il].attention_norm);
  1488. offload_func(cur);
  1489. ggml_set_name(cur, "attention_norm_0");
  1490. }
  1491. // self-attention
  1492. {
  1493. // compute Q and K and RoPE them
  1494. struct ggml_tensor * tmpk = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  1495. offload_func_kq(tmpk);
  1496. ggml_set_name(tmpk, "tmpk");
  1497. struct ggml_tensor * tmpq = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  1498. offload_func_kq(tmpq);
  1499. ggml_set_name(tmpq, "tmpq");
  1500. 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);
  1501. offload_func_kq(Kcur);
  1502. ggml_set_name(Kcur, "Kcur");
  1503. 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);
  1504. offload_func_kq(Qcur);
  1505. ggml_set_name(Qcur, "Qcur");
  1506. // store key and value to memory
  1507. {
  1508. // compute the transposed [N, n_embd] V matrix
  1509. struct ggml_tensor * tmpv = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  1510. offload_func_v(tmpv);
  1511. ggml_set_name(tmpv, "tmpv");
  1512. struct ggml_tensor * Vcur = ggml_transpose(ctx0, ggml_reshape_2d(ctx0, tmpv, n_embd_gqa, N));
  1513. offload_func_v(Vcur);
  1514. ggml_set_name(Vcur, "Vcur");
  1515. 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));
  1516. offload_func_kq(k);
  1517. ggml_set_name(k, "k");
  1518. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd_gqa,
  1519. ( n_ctx)*ggml_element_size(kv_self.v),
  1520. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd_gqa + n_past*ggml_element_size(kv_self.v));
  1521. offload_func_v(v);
  1522. ggml_set_name(v, "v");
  1523. // important: storing RoPE-ed version of K in the KV cache!
  1524. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
  1525. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
  1526. }
  1527. struct ggml_tensor * Q =
  1528. ggml_permute(ctx0,
  1529. Qcur,
  1530. 0, 2, 1, 3);
  1531. offload_func_kq(Q);
  1532. ggml_set_name(Q, "Q");
  1533. struct ggml_tensor * K =
  1534. ggml_view_3d(ctx0, kv_self.k,
  1535. n_embd_head, n_past + N, n_head_kv,
  1536. ggml_element_size(kv_self.k)*n_embd_gqa,
  1537. ggml_element_size(kv_self.k)*n_embd_head,
  1538. ggml_element_size(kv_self.k)*n_embd_gqa*n_ctx*il);
  1539. offload_func_kq(K);
  1540. ggml_set_name(K, "K");
  1541. // K * Q
  1542. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  1543. offload_func_kq(KQ);
  1544. ggml_set_name(KQ, "KQ");
  1545. // KQ_scaled = KQ / sqrt(n_embd_head)
  1546. // KQ_scaled shape [n_past + N, N, n_head, 1]
  1547. struct ggml_tensor * KQ_scaled = ggml_scale_inplace(ctx0, KQ, KQ_scale);
  1548. offload_func_kq(KQ_scaled);
  1549. ggml_set_name(KQ_scaled, "KQ_scaled");
  1550. // KQ_masked = mask_past(KQ_scaled)
  1551. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf_inplace(ctx0, KQ_scaled, n_past);
  1552. offload_func_kq(KQ_masked);
  1553. ggml_set_name(KQ_masked, "KQ_masked");
  1554. // KQ = soft_max(KQ_masked)
  1555. struct ggml_tensor * KQ_soft_max = ggml_soft_max_inplace(ctx0, KQ_masked);
  1556. offload_func_v(KQ_soft_max);
  1557. ggml_set_name(KQ_soft_max, "KQ_soft_max");
  1558. // split cached V into n_head heads
  1559. struct ggml_tensor * V =
  1560. ggml_view_3d(ctx0, kv_self.v,
  1561. n_past + N, n_embd_head, n_head_kv,
  1562. ggml_element_size(kv_self.v)*n_ctx,
  1563. ggml_element_size(kv_self.v)*n_ctx*n_embd_head,
  1564. ggml_element_size(kv_self.v)*n_ctx*n_embd_gqa*il);
  1565. offload_func_v(V);
  1566. ggml_set_name(V, "V");
  1567. #if 1
  1568. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  1569. offload_func_v(KQV);
  1570. ggml_set_name(KQV, "KQV");
  1571. #else
  1572. // make V contiguous in memory to speed up the matmul, however we waste time on the copy
  1573. // on M1 this is faster for the perplexity computation, but ~5% slower for the single-token generation
  1574. // is there a better way?
  1575. 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));
  1576. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V_cont, KQ_soft_max);
  1577. #endif
  1578. // KQV_merged = KQV.permute(0, 2, 1, 3)
  1579. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  1580. offload_func_v(KQV_merged);
  1581. ggml_set_name(KQV_merged, "KQV_merged");
  1582. // cur = KQV_merged.contiguous().view(n_embd, N)
  1583. cur = ggml_cpy(ctx0,
  1584. KQV_merged,
  1585. ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  1586. offload_func_v(cur);
  1587. ggml_set_name(cur, "KQV_merged_contiguous");
  1588. // projection (no bias)
  1589. cur = ggml_mul_mat(ctx0,
  1590. model.layers[il].wo,
  1591. cur);
  1592. offload_func(cur);
  1593. ggml_set_name(cur, "result_wo");
  1594. }
  1595. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  1596. offload_func(inpFF);
  1597. ggml_set_name(inpFF, "inpFF");
  1598. // feed-forward network
  1599. {
  1600. // norm
  1601. {
  1602. cur = ggml_rms_norm(ctx0, inpFF, norm_rms_eps);
  1603. offload_func(cur);
  1604. ggml_set_name(cur, "rms_norm_1");
  1605. // cur = cur*ffn_norm(broadcasted)
  1606. cur = ggml_mul(ctx0, cur, model.layers[il].ffn_norm);
  1607. offload_func(cur);
  1608. ggml_set_name(cur, "ffn_norm");
  1609. }
  1610. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  1611. model.layers[il].w3,
  1612. cur);
  1613. offload_func(tmp);
  1614. ggml_set_name(tmp, "result_w3");
  1615. cur = ggml_mul_mat(ctx0,
  1616. model.layers[il].w1,
  1617. cur);
  1618. offload_func(cur);
  1619. ggml_set_name(cur, "result_w1");
  1620. // SILU activation
  1621. cur = ggml_silu(ctx0, cur);
  1622. offload_func(cur);
  1623. ggml_set_name(cur, "silu");
  1624. cur = ggml_mul(ctx0, cur, tmp);
  1625. offload_func(cur);
  1626. ggml_set_name(cur, "silu_x_result_w3");
  1627. cur = ggml_mul_mat(ctx0,
  1628. model.layers[il].w2,
  1629. cur);
  1630. offload_func(cur);
  1631. ggml_set_name(cur, "result_w2");
  1632. }
  1633. cur = ggml_add(ctx0, cur, inpFF);
  1634. offload_func(cur);
  1635. ggml_set_name(cur, "inpFF_+_result_w2");
  1636. // input for next layer
  1637. inpL = cur;
  1638. }
  1639. // norm
  1640. {
  1641. cur = ggml_rms_norm(ctx0, inpL, norm_rms_eps);
  1642. offload_func_nr(cur);
  1643. ggml_set_name(cur, "rms_norm_2");
  1644. // cur = cur*norm(broadcasted)
  1645. cur = ggml_mul(ctx0, cur, model.norm);
  1646. // offload_func_nr(cur); // TODO CPU + GPU mirrored backend
  1647. ggml_set_name(cur, "result_norm");
  1648. }
  1649. // lm_head
  1650. cur = ggml_mul_mat(ctx0, model.output, cur);
  1651. ggml_set_name(cur, "result_output");
  1652. // logits -> probs
  1653. //cur = ggml_soft_max_inplace(ctx0, cur);
  1654. ggml_build_forward_expand(gf, cur);
  1655. if (mem_per_token == 0) {
  1656. mem_per_token = ggml_used_mem(ctx0)/N;
  1657. }
  1658. ggml_free(ctx0);
  1659. return gf;
  1660. }
  1661. // evaluate the transformer
  1662. //
  1663. // - lctx: llama context
  1664. // - tokens: new batch of tokens to process
  1665. // - embd embeddings input
  1666. // - n_tokens number of tokens
  1667. // - n_past: the context size so far
  1668. // - n_threads: number of threads to use
  1669. //
  1670. static bool llama_eval_internal(
  1671. llama_context & lctx,
  1672. const llama_token * tokens,
  1673. const float * embd,
  1674. int n_tokens,
  1675. int n_past,
  1676. int n_threads,
  1677. const char * cgraph_fname) {
  1678. GGML_ASSERT((!tokens && embd) || (tokens && !embd)); // NOLINT
  1679. GGML_ASSERT(n_tokens > 0);
  1680. GGML_ASSERT(n_past >= 0);
  1681. GGML_ASSERT(n_threads > 0);
  1682. // TODO: keep the values of n_batch and n_ctx
  1683. // GGML_ASSERT(n_tokens <= n_batch);
  1684. // GGML_ASSERT(n_past + n_tokens <= n_ctx);
  1685. const int64_t t_start_us = ggml_time_us();
  1686. #ifdef GGML_USE_MPI
  1687. ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  1688. #endif
  1689. const int N = n_tokens;
  1690. const auto & model = lctx.model;
  1691. const auto & hparams = model.hparams;
  1692. const auto & kv_self = lctx.kv_self;
  1693. GGML_ASSERT(!!kv_self.ctx);
  1694. const int64_t n_embd = hparams.n_embd;
  1695. const int64_t n_vocab = hparams.n_vocab;
  1696. ggml_allocr_reset(lctx.alloc);
  1697. ggml_cgraph * gf = llama_build_graph(lctx, tokens, embd, n_tokens, n_past);
  1698. ggml_allocr_alloc_graph(lctx.alloc, gf);
  1699. #ifdef GGML_USE_CUBLAS
  1700. for (int i = 0; i < gf->n_leafs; i++) {
  1701. ggml_tensor * node = gf->leafs[i];
  1702. if (node->backend == GGML_BACKEND_GPU && node->extra == NULL) {
  1703. ggml_cuda_assign_scratch_offset(node, (char*)node->data - (char *) lctx.buf_alloc.data);
  1704. }
  1705. }
  1706. for (int i = 0; i < gf->n_nodes; i++) {
  1707. ggml_tensor * node = gf->nodes[i];
  1708. if (node->backend == GGML_BACKEND_GPU && node->extra == NULL) {
  1709. ggml_cuda_assign_scratch_offset(node, (char*)node->data - (char *) lctx.buf_alloc.data);
  1710. }
  1711. }
  1712. #endif
  1713. // 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);
  1714. // for big prompts, if BLAS is enabled, it is better to use only one thread
  1715. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  1716. n_threads = N >= 32 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas() ? 1 : n_threads;
  1717. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  1718. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 2];
  1719. GGML_ASSERT(strcmp(res->name, "result_output") == 0);
  1720. GGML_ASSERT(strcmp(embeddings->name, "result_norm") == 0);
  1721. #if GGML_USE_MPI
  1722. const int64_t n_layer = hparams.n_layer;
  1723. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  1724. #endif
  1725. #ifdef GGML_USE_METAL
  1726. if (lctx.ctx_metal) {
  1727. ggml_metal_set_n_cb (lctx.ctx_metal, n_threads);
  1728. ggml_metal_graph_compute(lctx.ctx_metal, gf);
  1729. ggml_metal_get_tensor (lctx.ctx_metal, res);
  1730. if (!lctx.embedding.empty()) {
  1731. ggml_metal_get_tensor(lctx.ctx_metal, embeddings);
  1732. }
  1733. } else {
  1734. ggml_graph_compute_helper(lctx.work_buffer, gf, n_threads);
  1735. }
  1736. #else
  1737. ggml_graph_compute_helper(lctx.work_buffer, gf, n_threads);
  1738. #endif
  1739. #if GGML_USE_MPI
  1740. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  1741. #endif
  1742. // update kv token count
  1743. lctx.kv_self.n = n_past + N;
  1744. if (cgraph_fname) {
  1745. ggml_graph_export(gf, cgraph_fname);
  1746. }
  1747. #ifdef GGML_PERF
  1748. // print timing information per ggml operation (for debugging purposes)
  1749. // requires GGML_PERF to be defined
  1750. ggml_graph_print(gf);
  1751. #endif
  1752. // plot the computation graph in dot format (for debugging purposes)
  1753. //if (n_past%100 == 0) {
  1754. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  1755. //}
  1756. // extract logits
  1757. {
  1758. auto & logits_out = lctx.logits;
  1759. if (lctx.logits_all) {
  1760. logits_out.resize(n_vocab * N);
  1761. memcpy(logits_out.data(), (float *) ggml_get_data(res), sizeof(float)*n_vocab*N);
  1762. } else {
  1763. // return result for just the last token
  1764. logits_out.resize(n_vocab);
  1765. memcpy(logits_out.data(), (float *) ggml_get_data(res) + (n_vocab*(N-1)), sizeof(float)*n_vocab);
  1766. }
  1767. }
  1768. // extract embeddings
  1769. if (!lctx.embedding.empty()) {
  1770. auto & embedding_out = lctx.embedding;
  1771. embedding_out.resize(n_embd);
  1772. memcpy(embedding_out.data(), (float *) ggml_get_data(embeddings) + (n_embd*(N - 1)), sizeof(float)*n_embd);
  1773. }
  1774. // measure the performance only for the single-token evals
  1775. if (N == 1) {
  1776. lctx.t_eval_us += ggml_time_us() - t_start_us;
  1777. lctx.n_eval++;
  1778. }
  1779. else if (N > 1) {
  1780. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  1781. lctx.n_p_eval += N;
  1782. }
  1783. return true;
  1784. }
  1785. //
  1786. // tokenizer
  1787. //
  1788. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  1789. return vocab.type;
  1790. }
  1791. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  1792. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  1793. }
  1794. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  1795. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  1796. }
  1797. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  1798. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  1799. }
  1800. static bool llama_is_user_defined_token(const llama_vocab & vocab, llama_token id) {
  1801. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  1802. }
  1803. static bool llama_is_unused_token(const llama_vocab & vocab, llama_token id) {
  1804. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNUSED;
  1805. }
  1806. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  1807. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  1808. }
  1809. static bool llama_is_bos_token(const llama_vocab & vocab, llama_token id) {
  1810. GGML_ASSERT(llama_is_control_token(vocab, id));
  1811. return id == vocab.special_bos_id;
  1812. }
  1813. static bool llama_is_eos_token(const llama_vocab & vocab, llama_token id ) {
  1814. GGML_ASSERT(llama_is_control_token(vocab, id));
  1815. return id == vocab.special_eos_id;
  1816. }
  1817. static bool llama_is_pad_token(const llama_vocab & vocab, llama_token id ) {
  1818. GGML_ASSERT(id < 0 || llama_is_control_token(vocab, id));
  1819. return id == vocab.special_pad_id;
  1820. }
  1821. static uint8_t llama_token_to_byte(const llama_vocab & vocab, llama_token id) {
  1822. GGML_ASSERT(llama_is_byte_token(vocab, id));
  1823. const auto& token_data = vocab.id_to_token.at(id);
  1824. auto buf = token_data.text.substr(3, 2);
  1825. return strtol(buf.c_str(), NULL, 16);
  1826. }
  1827. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  1828. char buf[7];
  1829. int result = snprintf(buf, sizeof(buf), "<0x%02X>", ch);
  1830. GGML_ASSERT(0 <= result && result < 7);
  1831. return vocab.token_to_id.at(buf);
  1832. }
  1833. static std::string llama_escape_whitespace(const std::string& text) {
  1834. std::string result;
  1835. bool escaping = false;
  1836. result += "\xe2\x96\x81";
  1837. for (size_t offs = 0; offs < text.length(); ++offs) {
  1838. if (text[offs] == ' ') {
  1839. if (!escaping) {
  1840. result += "\xe2\x96\x81";
  1841. escaping = true;
  1842. }
  1843. }
  1844. else {
  1845. escaping = false;
  1846. result += text[offs];
  1847. }
  1848. }
  1849. return result;
  1850. }
  1851. static std::string llama_unescape_whitespace(const std::string& word) {
  1852. if (word.length() >= 3 && word.substr(0, 3) == "\xe2\x96\x81") {
  1853. return std::string(" ") + word.substr(3);
  1854. }
  1855. return word;
  1856. }
  1857. static size_t utf8_len(char src) {
  1858. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  1859. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  1860. return lookup[highbits];
  1861. }
  1862. struct llama_sp_symbol {
  1863. using index = int;
  1864. index prev;
  1865. index next;
  1866. const char * text;
  1867. size_t n;
  1868. };
  1869. static_assert(std::is_trivially_copyable<llama_sp_symbol>::value, "llama_sp_symbol is not trivially copyable");
  1870. struct llama_sp_bigram {
  1871. struct comparator {
  1872. bool operator()(llama_sp_bigram & l, llama_sp_bigram & r) {
  1873. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  1874. }
  1875. };
  1876. using queue_storage = std::vector<llama_sp_bigram>;
  1877. using queue = std::priority_queue<llama_sp_bigram, queue_storage, comparator>;
  1878. llama_sp_symbol::index left;
  1879. llama_sp_symbol::index right;
  1880. float score;
  1881. size_t size;
  1882. };
  1883. // original implementation:
  1884. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  1885. struct llama_tokenizer {
  1886. llama_tokenizer(const llama_vocab & vocab): vocab_(vocab) {}
  1887. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  1888. // split string into utf8 chars
  1889. int index = 0;
  1890. size_t offs = 0;
  1891. while (offs < text.size()) {
  1892. llama_sp_symbol sym;
  1893. size_t len = utf8_len(text[offs]);
  1894. GGML_ASSERT(offs + len <= text.size());
  1895. sym.text = text.c_str() + offs;
  1896. sym.n = len;
  1897. offs += len;
  1898. sym.prev = index - 1;
  1899. sym.next = offs == text.size() ? -1 : index + 1;
  1900. index++;
  1901. symbols_.emplace_back(sym);
  1902. }
  1903. // seed the work queue with all possible 2-character tokens.
  1904. for (size_t i = 1; i < symbols_.size(); ++i) {
  1905. try_add_bigram(i - 1, i);
  1906. }
  1907. // keep substituting the highest frequency pairs for as long as we can.
  1908. while (!work_queue_.empty()) {
  1909. auto bigram = work_queue_.top();
  1910. work_queue_.pop();
  1911. auto & left_sym = symbols_[bigram.left];
  1912. auto & right_sym = symbols_[bigram.right];
  1913. // if one of the symbols already got merged, skip it.
  1914. if (left_sym.n == 0 || right_sym.n == 0 ||
  1915. left_sym.n + right_sym.n != bigram.size) {
  1916. continue;
  1917. }
  1918. // merge the right sym into the left one
  1919. left_sym.n += right_sym.n;
  1920. right_sym.n = 0;
  1921. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  1922. // remove the right sym from the chain
  1923. left_sym.next = right_sym.next;
  1924. if (right_sym.next >= 0) {
  1925. symbols_[right_sym.next].prev = bigram.left;
  1926. }
  1927. // find more substitutions
  1928. try_add_bigram(left_sym.prev, bigram.left);
  1929. try_add_bigram(bigram.left, left_sym.next);
  1930. }
  1931. for (int i = 0; i != -1; i = symbols_[i].next) {
  1932. auto & symbol = symbols_[i];
  1933. resegment(symbol, output);
  1934. }
  1935. }
  1936. private:
  1937. void resegment(llama_sp_symbol &symbol, std::vector<llama_vocab::id> &output) {
  1938. auto text = std::string(symbol.text, symbol.n);
  1939. auto token = vocab_.token_to_id.find(text);
  1940. // Do we need to support is_unused?
  1941. if (token != vocab_.token_to_id.end()) {
  1942. output.push_back((*token).second);
  1943. return;
  1944. }
  1945. const auto p = rev_merge.find(text);
  1946. if (p == rev_merge.end()) {
  1947. // output any symbols that did not form tokens as bytes.
  1948. for (int j = 0; j < (int)symbol.n; ++j) {
  1949. llama_vocab::id token_id = llama_byte_to_token(vocab_, symbol.text[j]);
  1950. output.push_back(token_id);
  1951. }
  1952. return;
  1953. }
  1954. resegment(symbols_[p->second.first], output);
  1955. resegment(symbols_[p->second.second], output);
  1956. }
  1957. void try_add_bigram(int left, int right) {
  1958. if (left == -1 || right == -1) {
  1959. return;
  1960. }
  1961. const std::string text = std::string(symbols_[left].text, symbols_[left].n + symbols_[right].n);
  1962. auto token = vocab_.token_to_id.find(text);
  1963. if (token == vocab_.token_to_id.end()) {
  1964. return;
  1965. }
  1966. if (static_cast<size_t>((*token).second) >= vocab_.id_to_token.size()) {
  1967. return;
  1968. }
  1969. const auto &tok_data = vocab_.id_to_token[(*token).second];
  1970. llama_sp_bigram bigram;
  1971. bigram.left = left;
  1972. bigram.right = right;
  1973. bigram.score = tok_data.score;
  1974. bigram.size = text.size();
  1975. work_queue_.push(bigram);
  1976. // Do we need to support is_unused?
  1977. rev_merge[text] = std::make_pair(left, right);
  1978. }
  1979. const llama_vocab & vocab_;
  1980. std::vector<llama_sp_symbol> symbols_;
  1981. llama_sp_bigram::queue work_queue_;
  1982. std::map<std::string, std::pair<int, int> > rev_merge;
  1983. };
  1984. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, const std::string & raw_text, bool bos, bool escape) {
  1985. llama_tokenizer tokenizer(vocab);
  1986. std::vector<llama_vocab::id> output;
  1987. if (raw_text.empty()) {
  1988. return output;
  1989. }
  1990. if (bos) {
  1991. output.push_back(vocab.special_bos_id);
  1992. }
  1993. std::string text;
  1994. if (escape) {
  1995. text = llama_escape_whitespace(raw_text);
  1996. } else {
  1997. text = raw_text;
  1998. }
  1999. tokenizer.tokenize(text, output);
  2000. return output;
  2001. }
  2002. //
  2003. // grammar - internal
  2004. //
  2005. struct llama_partial_utf8 {
  2006. uint32_t value; // bit value so far (unshifted)
  2007. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  2008. };
  2009. struct llama_grammar {
  2010. const std::vector<std::vector<llama_grammar_element>> rules;
  2011. std::vector<std::vector<const llama_grammar_element *>> stacks;
  2012. // buffer for partially generated UTF-8 sequence from accepted tokens
  2013. llama_partial_utf8 partial_utf8;
  2014. };
  2015. struct llama_grammar_candidate {
  2016. size_t index;
  2017. const uint32_t * code_points;
  2018. llama_partial_utf8 partial_utf8;
  2019. };
  2020. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  2021. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  2022. std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  2023. const char * src,
  2024. llama_partial_utf8 partial_start) {
  2025. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  2026. const char * pos = src;
  2027. std::vector<uint32_t> code_points;
  2028. uint32_t value = partial_start.value;
  2029. int n_remain = partial_start.n_remain;
  2030. // continue previous decode, if applicable
  2031. while (*pos != 0 && n_remain > 0) {
  2032. uint8_t next_byte = static_cast<uint8_t>(*pos);
  2033. if ((next_byte >> 6) != 2) {
  2034. // invalid sequence, abort
  2035. code_points.push_back(0);
  2036. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  2037. }
  2038. value = (value << 6) + (next_byte & 0x3F);
  2039. ++pos;
  2040. --n_remain;
  2041. }
  2042. if (partial_start.n_remain > 0 && n_remain == 0) {
  2043. code_points.push_back(value);
  2044. }
  2045. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  2046. while (*pos != 0) {
  2047. uint8_t first_byte = static_cast<uint8_t>(*pos);
  2048. uint8_t highbits = first_byte >> 4;
  2049. n_remain = lookup[highbits] - 1;
  2050. if (n_remain < 0) {
  2051. // invalid sequence, abort
  2052. code_points.clear();
  2053. code_points.push_back(0);
  2054. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  2055. }
  2056. uint8_t mask = (1 << (7 - n_remain)) - 1;
  2057. value = first_byte & mask;
  2058. ++pos;
  2059. while (*pos != 0 && n_remain > 0) {
  2060. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  2061. ++pos;
  2062. --n_remain;
  2063. }
  2064. if (n_remain == 0) {
  2065. code_points.push_back(value);
  2066. }
  2067. }
  2068. code_points.push_back(0);
  2069. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  2070. }
  2071. // returns true iff pos points to the end of one of the definitions of a rule
  2072. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  2073. switch (pos->type) {
  2074. case LLAMA_GRETYPE_END: return true; // NOLINT
  2075. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  2076. default: return false;
  2077. }
  2078. }
  2079. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  2080. // asserts that pos is pointing to a char range element
  2081. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  2082. const llama_grammar_element * pos,
  2083. const uint32_t chr) {
  2084. bool found = false;
  2085. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  2086. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  2087. do {
  2088. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  2089. // inclusive range, e.g. [a-z]
  2090. found = found || (pos->value <= chr && chr <= pos[1].value);
  2091. pos += 2;
  2092. } else {
  2093. // exact char match, e.g. [a] or "a"
  2094. found = found || pos->value == chr;
  2095. pos += 1;
  2096. }
  2097. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  2098. return std::make_pair(found == is_positive_char, pos);
  2099. }
  2100. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  2101. // range at pos (regular or inverse range)
  2102. // asserts that pos is pointing to a char range element
  2103. static bool llama_grammar_match_partial_char(
  2104. const llama_grammar_element * pos,
  2105. const llama_partial_utf8 partial_utf8) {
  2106. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  2107. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  2108. uint32_t partial_value = partial_utf8.value;
  2109. int n_remain = partial_utf8.n_remain;
  2110. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  2111. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  2112. return false;
  2113. }
  2114. // range of possible code points this partial UTF-8 sequence could complete to
  2115. uint32_t low = partial_value << (n_remain * 6);
  2116. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  2117. if (low == 0) {
  2118. if (n_remain == 2) {
  2119. low = 1 << 11;
  2120. } else if (n_remain == 3) {
  2121. low = 1 << 16;
  2122. }
  2123. }
  2124. do {
  2125. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  2126. // inclusive range, e.g. [a-z]
  2127. if (pos->value <= high && low <= pos[1].value) {
  2128. return is_positive_char;
  2129. }
  2130. pos += 2;
  2131. } else {
  2132. // exact char match, e.g. [a] or "a"
  2133. if (low <= pos->value && pos->value <= high) {
  2134. return is_positive_char;
  2135. }
  2136. pos += 1;
  2137. }
  2138. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  2139. return !is_positive_char;
  2140. }
  2141. // transforms a grammar pushdown stack into N possible stacks, all ending
  2142. // at a character range (terminal element)
  2143. static void llama_grammar_advance_stack(
  2144. const std::vector<std::vector<llama_grammar_element>> & rules,
  2145. const std::vector<const llama_grammar_element *> & stack,
  2146. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  2147. if (stack.empty()) {
  2148. new_stacks.push_back(stack);
  2149. return;
  2150. }
  2151. const llama_grammar_element * pos = stack.back();
  2152. switch (pos->type) {
  2153. case LLAMA_GRETYPE_RULE_REF: {
  2154. const size_t rule_id = static_cast<size_t>(pos->value);
  2155. const llama_grammar_element * subpos = rules[rule_id].data();
  2156. do {
  2157. // init new stack without the top (pos)
  2158. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  2159. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  2160. // if this rule ref is followed by another element, add that to stack
  2161. new_stack.push_back(pos + 1);
  2162. }
  2163. if (!llama_grammar_is_end_of_sequence(subpos)) {
  2164. // if alternate is nonempty, add to stack
  2165. new_stack.push_back(subpos);
  2166. }
  2167. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  2168. while (!llama_grammar_is_end_of_sequence(subpos)) {
  2169. // scan to end of alternate def
  2170. subpos++;
  2171. }
  2172. if (subpos->type == LLAMA_GRETYPE_ALT) {
  2173. // there's another alternate def of this rule to process
  2174. subpos++;
  2175. } else {
  2176. break;
  2177. }
  2178. } while (true);
  2179. break;
  2180. }
  2181. case LLAMA_GRETYPE_CHAR:
  2182. case LLAMA_GRETYPE_CHAR_NOT:
  2183. new_stacks.push_back(stack);
  2184. break;
  2185. default:
  2186. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  2187. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  2188. // those
  2189. GGML_ASSERT(false);
  2190. }
  2191. }
  2192. // takes a set of possible pushdown stacks on a grammar, which are required to
  2193. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  2194. // produces the N possible stacks if the given char is accepted at those
  2195. // positions
  2196. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  2197. const std::vector<std::vector<llama_grammar_element>> & rules,
  2198. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  2199. const uint32_t chr) {
  2200. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  2201. for (const auto & stack : stacks) {
  2202. if (stack.empty()) {
  2203. continue;
  2204. }
  2205. auto match = llama_grammar_match_char(stack.back(), chr);
  2206. if (match.first) {
  2207. const llama_grammar_element * pos = match.second;
  2208. // update top of stack to next element, if any
  2209. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  2210. if (!llama_grammar_is_end_of_sequence(pos)) {
  2211. new_stack.push_back(pos);
  2212. }
  2213. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  2214. }
  2215. }
  2216. return new_stacks;
  2217. }
  2218. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  2219. const std::vector<std::vector<llama_grammar_element>> & rules,
  2220. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  2221. const std::vector<llama_grammar_candidate> & candidates);
  2222. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  2223. const std::vector<std::vector<llama_grammar_element>> & rules,
  2224. const std::vector<const llama_grammar_element *> & stack,
  2225. const std::vector<llama_grammar_candidate> & candidates) {
  2226. std::vector<llama_grammar_candidate> rejects;
  2227. if (stack.empty()) {
  2228. for (auto tok : candidates) {
  2229. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  2230. rejects.push_back(tok);
  2231. }
  2232. }
  2233. return rejects;
  2234. }
  2235. const llama_grammar_element * stack_pos = stack.back();
  2236. std::vector<llama_grammar_candidate> next_candidates;
  2237. for (auto tok : candidates) {
  2238. if (*tok.code_points == 0) {
  2239. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  2240. // that cannot satisfy this position in grammar
  2241. if (tok.partial_utf8.n_remain != 0 &&
  2242. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  2243. rejects.push_back(tok);
  2244. }
  2245. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  2246. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  2247. } else {
  2248. rejects.push_back(tok);
  2249. }
  2250. }
  2251. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  2252. // update top of stack to next element, if any
  2253. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  2254. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  2255. stack_after.push_back(stack_pos_after);
  2256. }
  2257. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  2258. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  2259. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  2260. for (auto tok : next_rejects) {
  2261. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  2262. }
  2263. return rejects;
  2264. }
  2265. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  2266. const std::vector<std::vector<llama_grammar_element>> & rules,
  2267. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  2268. const std::vector<llama_grammar_candidate> & candidates) {
  2269. GGML_ASSERT(!stacks.empty()); // REVIEW
  2270. if (candidates.empty()) {
  2271. return std::vector<llama_grammar_candidate>();
  2272. }
  2273. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  2274. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  2275. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  2276. }
  2277. return rejects;
  2278. }
  2279. //
  2280. // grammar - external
  2281. //
  2282. struct llama_grammar * llama_grammar_init(
  2283. const llama_grammar_element ** rules,
  2284. size_t n_rules,
  2285. size_t start_rule_index) {
  2286. const llama_grammar_element * pos;
  2287. // copy rule definitions into vectors
  2288. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  2289. for (size_t i = 0; i < n_rules; i++) {
  2290. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  2291. vec_rules[i].push_back(*pos);
  2292. }
  2293. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  2294. }
  2295. // loop over alternates of start rule to build initial stacks
  2296. std::vector<std::vector<const llama_grammar_element *>> stacks;
  2297. pos = rules[start_rule_index];
  2298. do {
  2299. std::vector<const llama_grammar_element *> stack;
  2300. if (!llama_grammar_is_end_of_sequence(pos)) {
  2301. // if alternate is nonempty, add to stack
  2302. stack.push_back(pos);
  2303. }
  2304. llama_grammar_advance_stack(vec_rules, stack, stacks);
  2305. while (!llama_grammar_is_end_of_sequence(pos)) {
  2306. // scan to end of alternate def
  2307. pos++;
  2308. }
  2309. if (pos->type == LLAMA_GRETYPE_ALT) {
  2310. // there's another alternate def of this rule to process
  2311. pos++;
  2312. } else {
  2313. break;
  2314. }
  2315. } while (true);
  2316. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  2317. }
  2318. void llama_grammar_free(struct llama_grammar * grammar) {
  2319. delete grammar;
  2320. }
  2321. //
  2322. // sampling
  2323. //
  2324. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  2325. GGML_ASSERT(candidates->size > 0);
  2326. const int64_t t_start_sample_us = ggml_time_us();
  2327. // Sort the logits in descending order
  2328. if (!candidates->sorted) {
  2329. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  2330. return a.logit > b.logit;
  2331. });
  2332. candidates->sorted = true;
  2333. }
  2334. float max_l = candidates->data[0].logit;
  2335. float cum_sum = 0.0f;
  2336. for (size_t i = 0; i < candidates->size; ++i) {
  2337. float p = expf(candidates->data[i].logit - max_l);
  2338. candidates->data[i].p = p;
  2339. cum_sum += p;
  2340. }
  2341. for (size_t i = 0; i < candidates->size; ++i) {
  2342. candidates->data[i].p /= cum_sum;
  2343. }
  2344. if (ctx) {
  2345. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2346. }
  2347. }
  2348. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int k, size_t min_keep) {
  2349. const int64_t t_start_sample_us = ggml_time_us();
  2350. k = std::max(k, (int) min_keep);
  2351. k = std::min(k, (int) candidates->size);
  2352. // Sort scores in descending order
  2353. if (!candidates->sorted) {
  2354. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  2355. return a.logit > b.logit;
  2356. };
  2357. if (k == (int) candidates->size) {
  2358. std::sort(candidates->data, candidates->data + candidates->size, comp);
  2359. } else {
  2360. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  2361. }
  2362. candidates->sorted = true;
  2363. }
  2364. candidates->size = k;
  2365. if (ctx) {
  2366. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2367. }
  2368. }
  2369. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  2370. if (p >= 1.0f) {
  2371. return;
  2372. }
  2373. llama_sample_softmax(ctx, candidates);
  2374. const int64_t t_start_sample_us = ggml_time_us();
  2375. // Compute the cumulative probabilities
  2376. float cum_sum = 0.0f;
  2377. size_t last_idx = candidates->size;
  2378. for (size_t i = 0; i < candidates->size; ++i) {
  2379. cum_sum += candidates->data[i].p;
  2380. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  2381. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  2382. if (cum_sum >= p && i + 1 >= min_keep) {
  2383. last_idx = i + 1;
  2384. break;
  2385. }
  2386. }
  2387. // Resize the output vector to keep only the top-p tokens
  2388. candidates->size = last_idx;
  2389. if (ctx) {
  2390. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2391. }
  2392. }
  2393. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  2394. if (z >= 1.0f || candidates->size <= 2) {
  2395. return;
  2396. }
  2397. llama_sample_softmax(nullptr, candidates);
  2398. const int64_t t_start_sample_us = ggml_time_us();
  2399. // Compute the first and second derivatives
  2400. std::vector<float> first_derivatives(candidates->size - 1);
  2401. std::vector<float> second_derivatives(candidates->size - 2);
  2402. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  2403. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  2404. }
  2405. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  2406. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  2407. }
  2408. // Calculate absolute value of second derivatives
  2409. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  2410. second_derivatives[i] = abs(second_derivatives[i]);
  2411. }
  2412. // Normalize the second derivatives
  2413. {
  2414. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  2415. if (second_derivatives_sum > 1e-6f) {
  2416. for (float & value : second_derivatives) {
  2417. value /= second_derivatives_sum;
  2418. }
  2419. } else {
  2420. for (float & value : second_derivatives) {
  2421. value = 1.0f / second_derivatives.size();
  2422. }
  2423. }
  2424. }
  2425. float cum_sum = 0.0f;
  2426. size_t last_idx = candidates->size;
  2427. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  2428. cum_sum += second_derivatives[i];
  2429. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  2430. if (cum_sum > z && i >= min_keep) {
  2431. last_idx = i;
  2432. break;
  2433. }
  2434. }
  2435. // Resize the output vector to keep only the tokens above the tail location
  2436. candidates->size = last_idx;
  2437. if (ctx) {
  2438. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2439. }
  2440. }
  2441. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  2442. // Reference implementation:
  2443. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  2444. if (p >= 1.0f) {
  2445. return;
  2446. }
  2447. // Compute the softmax of logits and calculate entropy
  2448. llama_sample_softmax(nullptr, candidates);
  2449. const int64_t t_start_sample_us = ggml_time_us();
  2450. float entropy = 0.0f;
  2451. for (size_t i = 0; i < candidates->size; ++i) {
  2452. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  2453. }
  2454. // Compute the absolute difference between negative log probability and entropy for each candidate
  2455. std::vector<float> shifted_scores;
  2456. for (size_t i = 0; i < candidates->size; ++i) {
  2457. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  2458. shifted_scores.push_back(shifted_score);
  2459. }
  2460. // Sort tokens based on the shifted_scores and their corresponding indices
  2461. std::vector<size_t> indices(candidates->size);
  2462. std::iota(indices.begin(), indices.end(), 0);
  2463. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  2464. return shifted_scores[a] < shifted_scores[b];
  2465. });
  2466. // Compute the cumulative probabilities
  2467. float cum_sum = 0.0f;
  2468. size_t last_idx = indices.size();
  2469. for (size_t i = 0; i < indices.size(); ++i) {
  2470. size_t idx = indices[i];
  2471. cum_sum += candidates->data[idx].p;
  2472. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  2473. if (cum_sum > p && i >= min_keep - 1) {
  2474. last_idx = i + 1;
  2475. break;
  2476. }
  2477. }
  2478. // Resize the output vector to keep only the locally typical tokens
  2479. std::vector<llama_token_data> new_candidates;
  2480. for (size_t i = 0; i < last_idx; ++i) {
  2481. size_t idx = indices[i];
  2482. new_candidates.push_back(candidates->data[idx]);
  2483. }
  2484. // Replace the data in candidates with the new_candidates data
  2485. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  2486. candidates->size = new_candidates.size();
  2487. if (ctx) {
  2488. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2489. }
  2490. }
  2491. void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  2492. const int64_t t_start_sample_us = ggml_time_us();
  2493. for (size_t i = 0; i < candidates_p->size; ++i) {
  2494. candidates_p->data[i].logit /= temp;
  2495. }
  2496. if (ctx) {
  2497. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2498. }
  2499. }
  2500. 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) {
  2501. if (last_tokens_size == 0 || penalty == 1.0f) {
  2502. return;
  2503. }
  2504. const int64_t t_start_sample_us = ggml_time_us();
  2505. for (size_t i = 0; i < candidates->size; ++i) {
  2506. const auto * token_iter = std::find(last_tokens, last_tokens + last_tokens_size, candidates->data[i].id);
  2507. if (token_iter == last_tokens + last_tokens_size) {
  2508. continue;
  2509. }
  2510. // 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.
  2511. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  2512. if (candidates->data[i].logit <= 0) {
  2513. candidates->data[i].logit *= penalty;
  2514. } else {
  2515. candidates->data[i].logit /= penalty;
  2516. }
  2517. }
  2518. candidates->sorted = false;
  2519. if (ctx) {
  2520. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2521. }
  2522. }
  2523. 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) {
  2524. if (last_tokens_size == 0 || (alpha_frequency == 0.0f && alpha_presence == 0.0f)) {
  2525. return;
  2526. }
  2527. const int64_t t_start_sample_us = ggml_time_us();
  2528. // Create a frequency map to count occurrences of each token in last_tokens
  2529. std::unordered_map<llama_token, int> token_count;
  2530. for (size_t i = 0; i < last_tokens_size; ++i) {
  2531. token_count[last_tokens_p[i]]++;
  2532. }
  2533. // Apply frequency and presence penalties to the candidates
  2534. for (size_t i = 0; i < candidates->size; ++i) {
  2535. auto token_iter = token_count.find(candidates->data[i].id);
  2536. if (token_iter == token_count.end()) {
  2537. continue;
  2538. }
  2539. int count = token_iter->second;
  2540. candidates->data[i].logit -= float(count) * alpha_frequency + float(count > 0) * alpha_presence;
  2541. }
  2542. candidates->sorted = false;
  2543. if (ctx) {
  2544. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2545. }
  2546. }
  2547. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  2548. GGML_ASSERT(ctx);
  2549. const int64_t t_start_sample_us = ggml_time_us();
  2550. bool allow_eos = false;
  2551. for (const auto & stack : grammar->stacks) {
  2552. if (stack.empty()) {
  2553. allow_eos = true;
  2554. break;
  2555. }
  2556. }
  2557. const llama_token eos = llama_token_eos(ctx);
  2558. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  2559. std::vector<llama_grammar_candidate> candidates_grammar;
  2560. for (size_t i = 0; i < candidates->size; ++i) {
  2561. const llama_token id = candidates->data[i].id;
  2562. const std::string text = llama_token_to_text(ctx, id);
  2563. if (id == eos) {
  2564. if (!allow_eos) {
  2565. candidates->data[i].logit = -INFINITY;
  2566. }
  2567. } else if (text.empty()) {
  2568. candidates->data[i].logit = -INFINITY;
  2569. } else {
  2570. candidates_decoded.push_back(decode_utf8(text.c_str(), grammar->partial_utf8));
  2571. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  2572. }
  2573. }
  2574. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  2575. for (const auto & reject : rejects) {
  2576. candidates->data[reject.index].logit = -INFINITY;
  2577. }
  2578. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2579. }
  2580. static void llama_log_softmax(float * array, size_t size) {
  2581. float max_l = *std::max_element(array, array + size);
  2582. float sum = 0.f;
  2583. for (size_t i = 0; i < size; ++i) {
  2584. float p = expf(array[i] - max_l);
  2585. sum += p;
  2586. array[i] = p;
  2587. }
  2588. for (size_t i = 0; i < size; ++i) {
  2589. array[i] = logf(array[i] / sum);
  2590. }
  2591. }
  2592. void llama_sample_classifier_free_guidance(
  2593. struct llama_context * ctx,
  2594. llama_token_data_array * candidates,
  2595. struct llama_context * guidance_ctx,
  2596. float scale) {
  2597. int64_t t_start_sample_us = ggml_time_us();
  2598. GGML_ASSERT(ctx);
  2599. auto n_vocab = llama_n_vocab(ctx);
  2600. GGML_ASSERT(n_vocab == (int)candidates->size);
  2601. GGML_ASSERT(!candidates->sorted);
  2602. std::vector<float> logits_base;
  2603. logits_base.reserve(candidates->size);
  2604. for (size_t i = 0; i < candidates->size; ++i) {
  2605. logits_base.push_back(candidates->data[i].logit);
  2606. }
  2607. llama_log_softmax(logits_base.data(), candidates->size);
  2608. float* logits_guidance = llama_get_logits(guidance_ctx);
  2609. llama_log_softmax(logits_guidance, n_vocab);
  2610. for (int i = 0; i < n_vocab; ++i) {
  2611. float logit_guidance = logits_guidance[i];
  2612. float logit_base = logits_base[i];
  2613. candidates->data[i].logit = scale * (logit_base - logit_guidance) + logit_guidance;
  2614. }
  2615. if (ctx) {
  2616. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2617. }
  2618. }
  2619. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int m, float * mu) {
  2620. GGML_ASSERT(ctx);
  2621. auto N = float(llama_n_vocab(ctx));
  2622. int64_t t_start_sample_us;
  2623. t_start_sample_us = ggml_time_us();
  2624. llama_sample_softmax(nullptr, candidates);
  2625. // Estimate s_hat using the most probable m tokens
  2626. float s_hat = 0.0;
  2627. float sum_ti_bi = 0.0;
  2628. float sum_ti_sq = 0.0;
  2629. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  2630. float t_i = logf(float(i + 2) / float(i + 1));
  2631. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  2632. sum_ti_bi += t_i * b_i;
  2633. sum_ti_sq += t_i * t_i;
  2634. }
  2635. s_hat = sum_ti_bi / sum_ti_sq;
  2636. // Compute k from the estimated s_hat and target surprise value
  2637. float epsilon_hat = s_hat - 1;
  2638. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  2639. // Sample the next word X using top-k sampling
  2640. llama_sample_top_k(nullptr, candidates, int(k), 1);
  2641. if (ctx) {
  2642. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2643. }
  2644. llama_token X = llama_sample_token(ctx, candidates);
  2645. t_start_sample_us = ggml_time_us();
  2646. // Compute error as the difference between observed surprise and target surprise value
  2647. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  2648. return candidate.id == X;
  2649. }));
  2650. float observed_surprise = -log2f(candidates->data[X_idx].p);
  2651. float e = observed_surprise - tau;
  2652. // Update mu using the learning rate and error
  2653. *mu = *mu - eta * e;
  2654. if (ctx) {
  2655. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2656. }
  2657. return X;
  2658. }
  2659. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  2660. int64_t t_start_sample_us;
  2661. t_start_sample_us = ggml_time_us();
  2662. llama_sample_softmax(ctx, candidates);
  2663. // Truncate the words with surprise values greater than mu
  2664. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  2665. return -log2f(candidate.p) > *mu;
  2666. }));
  2667. if (candidates->size == 0) {
  2668. candidates->size = 1;
  2669. }
  2670. if (ctx) {
  2671. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2672. }
  2673. // Normalize the probabilities of the remaining words
  2674. llama_sample_softmax(ctx, candidates);
  2675. // Sample the next word X from the remaining words
  2676. llama_token X = llama_sample_token(ctx, candidates);
  2677. t_start_sample_us = ggml_time_us();
  2678. // Compute error as the difference between observed surprise and target surprise value
  2679. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  2680. return candidate.id == X;
  2681. }));
  2682. float observed_surprise = -log2f(candidates->data[X_idx].p);
  2683. float e = observed_surprise - tau;
  2684. // Update mu using the learning rate and error
  2685. *mu = *mu - eta * e;
  2686. if (ctx) {
  2687. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2688. }
  2689. return X;
  2690. }
  2691. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  2692. const int64_t t_start_sample_us = ggml_time_us();
  2693. // Find max element
  2694. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  2695. return a.logit < b.logit;
  2696. });
  2697. llama_token result = max_iter->id;
  2698. if (ctx) {
  2699. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2700. ctx->n_sample++;
  2701. }
  2702. return result;
  2703. }
  2704. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  2705. GGML_ASSERT(ctx);
  2706. const int64_t t_start_sample_us = ggml_time_us();
  2707. llama_sample_softmax(nullptr, candidates);
  2708. std::vector<float> probs;
  2709. probs.reserve(candidates->size);
  2710. for (size_t i = 0; i < candidates->size; ++i) {
  2711. probs.push_back(candidates->data[i].p);
  2712. }
  2713. std::discrete_distribution<> dist(probs.begin(), probs.end());
  2714. auto & rng = ctx->rng;
  2715. int idx = dist(rng);
  2716. llama_token result = candidates->data[idx].id;
  2717. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2718. ctx->n_sample++;
  2719. return result;
  2720. }
  2721. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  2722. const int64_t t_start_sample_us = ggml_time_us();
  2723. if (token == llama_token_eos(ctx)) {
  2724. for (const auto & stack : grammar->stacks) {
  2725. if (stack.empty()) {
  2726. return;
  2727. }
  2728. }
  2729. GGML_ASSERT(false);
  2730. }
  2731. const std::string text = llama_token_to_text(ctx, token);
  2732. // Note terminating 0 in decoded string
  2733. const auto decoded = decode_utf8(text.c_str(), grammar->partial_utf8);
  2734. const auto & code_points = decoded.first;
  2735. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  2736. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  2737. }
  2738. grammar->partial_utf8 = decoded.second;
  2739. GGML_ASSERT(!grammar->stacks.empty());
  2740. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2741. }
  2742. //
  2743. // quantization
  2744. //
  2745. static void llama_convert_tensor_internal(struct ggml_tensor * tensor, std::vector<float> & output, const size_t nelements, const int nthread) {
  2746. if (output.size() < nelements) {
  2747. output.resize(nelements);
  2748. }
  2749. float * f32_output = (float *) output.data();
  2750. ggml_type_traits_t qtype;
  2751. if (ggml_is_quantized(tensor->type)) {
  2752. qtype = ggml_internal_get_type_traits(tensor->type);
  2753. if (qtype.to_float == NULL) {
  2754. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  2755. }
  2756. } else if (tensor->type != GGML_TYPE_F16) {
  2757. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  2758. }
  2759. if (nthread < 2) {
  2760. if (tensor->type == GGML_TYPE_F16) {
  2761. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  2762. } else if (ggml_is_quantized(tensor->type)) {
  2763. qtype.to_float(tensor->data, f32_output, nelements);
  2764. } else {
  2765. GGML_ASSERT(false); // unreachable
  2766. }
  2767. return;
  2768. }
  2769. auto block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  2770. auto block_size_bytes = ggml_type_size(tensor->type);
  2771. GGML_ASSERT(nelements % block_size == 0);
  2772. auto nblocks = nelements / block_size;
  2773. auto blocks_per_thread = nblocks / nthread;
  2774. auto spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  2775. std::vector<std::thread> workers;
  2776. for (auto tnum = 0, in_buff_offs = 0, out_buff_offs = 0; tnum < nthread; tnum++) {
  2777. auto thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  2778. auto thr_elems = thr_blocks * block_size; // number of elements for this thread
  2779. auto thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  2780. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  2781. if (typ == GGML_TYPE_F16) {
  2782. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  2783. } else {
  2784. qtype.to_float(inbuf, outbuf, nels);
  2785. }
  2786. };
  2787. workers.push_back(std::thread(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems));
  2788. in_buff_offs += thr_block_bytes;
  2789. out_buff_offs += thr_elems;
  2790. }
  2791. for (auto & worker : workers) {
  2792. worker.join();
  2793. }
  2794. }
  2795. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  2796. ggml_type quantized_type;
  2797. llama_ftype ftype = params->ftype;
  2798. switch (params->ftype) {
  2799. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  2800. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  2801. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  2802. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  2803. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  2804. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  2805. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  2806. #ifdef GGML_USE_K_QUANTS
  2807. // K-quants
  2808. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  2809. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  2810. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  2811. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  2812. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  2813. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  2814. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  2815. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  2816. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  2817. #endif
  2818. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  2819. }
  2820. int nthread = params->nthread;
  2821. if (nthread <= 0) {
  2822. nthread = std::thread::hardware_concurrency();
  2823. }
  2824. std::unique_ptr<llama_model_loader> model_loader(new llama_model_loader(fname_inp, /*use_mmap*/ false));
  2825. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  2826. struct gguf_context * ctx_out = gguf_init_empty();
  2827. // copy the KV pairs from the input file
  2828. gguf_set_kv (ctx_out, model_loader->ctx_gguf);
  2829. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  2830. #ifdef GGML_USE_K_QUANTS
  2831. int n_attention_wv = 0;
  2832. int n_feed_forward_w2 = 0;
  2833. for (int i = 0; i < model_loader->n_tensors; ++i) {
  2834. struct ggml_tensor * meta = model_loader->get_tensor_meta(i);
  2835. const std::string name = ggml_get_name(meta);
  2836. // TODO: avoid hardcoded tensor names - use the TN_* constants
  2837. if (name.find("attn_v.weight") != std::string::npos) {
  2838. ++n_attention_wv;
  2839. }
  2840. else if (name.find("ffn_down.weight") != std::string::npos) {
  2841. ++n_feed_forward_w2;
  2842. }
  2843. }
  2844. int i_attention_wv = 0;
  2845. int i_feed_forward_w2 = 0;
  2846. #endif
  2847. size_t total_size_org = 0;
  2848. size_t total_size_new = 0;
  2849. std::vector<int64_t> hist_all(1 << 4, 0);
  2850. std::vector<std::thread> workers;
  2851. std::mutex mutex;
  2852. auto use_more_bits = [] (int i_layer, int num_layers) -> bool {
  2853. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  2854. };
  2855. int idx = 0;
  2856. std::vector<uint8_t> read_data;
  2857. std::vector<uint8_t> work;
  2858. // populate the original tensors so we get an initial meta data
  2859. for (int i = 0; i < model_loader->n_tensors; ++i) {
  2860. struct ggml_tensor * meta = model_loader->get_tensor_meta(i);
  2861. gguf_add_tensor(ctx_out, meta);
  2862. }
  2863. std::ofstream fout(fname_out, std::ios::binary);
  2864. const size_t meta_size = gguf_get_meta_size(ctx_out);
  2865. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  2866. // placeholder for the meta data
  2867. ::zeros(fout, meta_size);
  2868. for (int i = 0; i < model_loader->n_tensors; ++i) {
  2869. struct ggml_tensor * tensor = model_loader->get_tensor_meta(i);
  2870. const std::string name = ggml_get_name(tensor);
  2871. read_data.resize(ggml_nbytes(tensor));
  2872. tensor->data = read_data.data();
  2873. model_loader->load_data_for(tensor);
  2874. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  2875. ++idx, model_loader->n_tensors,
  2876. ggml_get_name(tensor),
  2877. llama_format_tensor_shape(tensor).c_str(),
  2878. ggml_type_name(tensor->type));
  2879. // This used to be a regex, but <regex> has an extreme cost to compile times.
  2880. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  2881. // quantize only 2D tensors
  2882. quantize &= (tensor->n_dims == 2);
  2883. quantize &= params->quantize_output_tensor || name != "output.weight";
  2884. quantize &= quantized_type != tensor->type;
  2885. enum ggml_type new_type;
  2886. void * new_data;
  2887. size_t new_size;
  2888. if (!quantize) {
  2889. new_type = tensor->type;
  2890. new_data = tensor->data;
  2891. new_size = ggml_nbytes(tensor);
  2892. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  2893. } else {
  2894. new_type = quantized_type;
  2895. #ifdef GGML_USE_K_QUANTS
  2896. // TODO: avoid hardcoded tensor names - use the TN_* constants
  2897. if (name == TN_OUTPUT) {
  2898. int nx = tensor->ne[0];
  2899. int ny = tensor->ne[1];
  2900. if (nx % QK_K == 0 && ny % QK_K == 0) {
  2901. new_type = GGML_TYPE_Q6_K;
  2902. }
  2903. } else if (name.find("attn_v.weight") != std::string::npos) {
  2904. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  2905. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  2906. new_type = i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  2907. }
  2908. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  2909. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  2910. use_more_bits(i_attention_wv, n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  2911. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  2912. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  2913. (i_attention_wv < n_attention_wv/8 || i_attention_wv >= 7*n_attention_wv/8)) new_type = GGML_TYPE_Q6_K;
  2914. ++i_attention_wv;
  2915. } else if (name.find("ffn_down.weight") != std::string::npos) {
  2916. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  2917. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  2918. new_type = i_feed_forward_w2 < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  2919. }
  2920. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  2921. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  2922. use_more_bits(i_feed_forward_w2, n_feed_forward_w2)) new_type = GGML_TYPE_Q6_K;
  2923. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && i_feed_forward_w2 < 4) new_type = GGML_TYPE_Q5_K;
  2924. ++i_feed_forward_w2;
  2925. } else if (name.find("attn_output.weight") != std::string::npos) {
  2926. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  2927. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) new_type = GGML_TYPE_Q4_K;
  2928. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  2929. }
  2930. else if (name.find("ffn_gate.weight") != std::string::npos || name.find("ffn_up.weight") != std::string::npos) {
  2931. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  2932. }
  2933. // This can be used to reduce the size of the Q5_K_S model.
  2934. // The associated PPL increase is fully in line with the size reduction
  2935. //else {
  2936. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  2937. //}
  2938. bool convert_incompatible_tensor = false;
  2939. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  2940. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K) {
  2941. int nx = tensor->ne[0];
  2942. int ny = tensor->ne[1];
  2943. if (nx % QK_K != 0 || ny % QK_K != 0) {
  2944. LLAMA_LOG_INFO("\n\nTensor sizes %d x %d are not divisible by %d, required for k-quants.\n",nx,ny,QK_K);
  2945. convert_incompatible_tensor = true;
  2946. }
  2947. }
  2948. if (convert_incompatible_tensor) {
  2949. if (name == TN_OUTPUT) {
  2950. new_type = GGML_TYPE_F16; //fall back to F16 instead of just failing.
  2951. LLAMA_LOG_WARN("F16 will be used for this tensor instead.\n");
  2952. } else if (name == TN_TOKEN_EMBD) {
  2953. new_type = GGML_TYPE_Q4_0; //fall back to Q4_0 instead of just failing.
  2954. LLAMA_LOG_WARN("Q4_0 will be used for this tensor instead.\n");
  2955. } else {
  2956. throw std::runtime_error("Unsupported tensor size encountered\n");
  2957. }
  2958. }
  2959. #endif
  2960. const size_t nelements = ggml_nelements(tensor);
  2961. float * f32_data;
  2962. std::vector<float> f32_conv_buf;
  2963. if (tensor->type == GGML_TYPE_F32) {
  2964. f32_data = (float *) tensor->data;
  2965. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  2966. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  2967. } else {
  2968. llama_convert_tensor_internal(tensor, f32_conv_buf, nelements, nthread);
  2969. f32_data = (float *) f32_conv_buf.data();
  2970. }
  2971. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  2972. fflush(stdout);
  2973. work.resize(nelements * 4); // upper bound on size
  2974. new_data = work.data();
  2975. std::vector<int64_t> hist_cur(1 << 4, 0);
  2976. static const int chunk_size = 32 * 512;
  2977. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  2978. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  2979. if (nthread_use < 2) {
  2980. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nelements, hist_cur.data());
  2981. } else {
  2982. size_t counter = 0;
  2983. new_size = 0;
  2984. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, nelements]() {
  2985. std::vector<int64_t> local_hist;
  2986. size_t local_size = 0;
  2987. while (true) {
  2988. std::unique_lock<std::mutex> lock(mutex);
  2989. size_t first = counter; counter += chunk_size;
  2990. if (first >= nelements) {
  2991. if (!local_hist.empty()) {
  2992. for (int j=0; j<int(local_hist.size()); ++j) {
  2993. hist_cur[j] += local_hist[j];
  2994. }
  2995. new_size += local_size;
  2996. }
  2997. break;
  2998. }
  2999. lock.unlock();
  3000. size_t last = std::min(nelements, first + chunk_size);
  3001. if (local_hist.empty()) {
  3002. local_hist.resize(hist_cur.size(), 0);
  3003. }
  3004. local_size += ggml_quantize_chunk(new_type, f32_data, new_data, first, last - first, local_hist.data());
  3005. }
  3006. };
  3007. if ((int) workers.size() < nthread_use - 1) {
  3008. workers.resize(nthread_use - 1);
  3009. }
  3010. for (int it = 0; it < nthread_use - 1; ++it) {
  3011. workers[it] = std::thread(compute);
  3012. }
  3013. compute();
  3014. for (int it = 0; it < nthread_use - 1; ++it) {
  3015. workers[it].join();
  3016. }
  3017. }
  3018. LLAMA_LOG_INFO("size = %8.2f MB -> %8.2f MB | hist: ", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  3019. int64_t tot_count = 0;
  3020. for (size_t i = 0; i < hist_cur.size(); i++) {
  3021. hist_all[i] += hist_cur[i];
  3022. tot_count += hist_cur[i];
  3023. }
  3024. if (tot_count > 0) {
  3025. for (size_t i = 0; i < hist_cur.size(); i++) {
  3026. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  3027. }
  3028. }
  3029. LLAMA_LOG_INFO("\n");
  3030. }
  3031. total_size_org += ggml_nbytes(tensor);
  3032. total_size_new += new_size;
  3033. // update the gguf meta data as we go
  3034. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  3035. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  3036. // write tensor data + padding
  3037. fout.write((const char *) new_data, new_size);
  3038. zeros(fout, GGML_PAD(new_size, align) - new_size);
  3039. }
  3040. // go back to beginning of file and write the updated meta data
  3041. {
  3042. fout.seekp(0);
  3043. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  3044. gguf_get_meta_data(ctx_out, data.data());
  3045. fout.write((const char *) data.data(), data.size());
  3046. }
  3047. fout.close();
  3048. gguf_free(ctx_out);
  3049. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  3050. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  3051. // print histogram for all tensors
  3052. {
  3053. int64_t sum_all = 0;
  3054. for (size_t i = 0; i < hist_all.size(); i++) {
  3055. sum_all += hist_all[i];
  3056. }
  3057. if (sum_all > 0) {
  3058. LLAMA_LOG_INFO("%s: hist: ", __func__);
  3059. for (size_t i = 0; i < hist_all.size(); i++) {
  3060. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  3061. }
  3062. LLAMA_LOG_INFO("\n");
  3063. }
  3064. }
  3065. }
  3066. // TODO: after the GGUF PR, this likely won't work and needs to be updated
  3067. int llama_apply_lora_from_file_internal(const struct llama_model & model, const char * path_lora, const char * path_base_model, int n_threads) {
  3068. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  3069. const int64_t t_start_lora_us = ggml_time_us();
  3070. auto fin = std::ifstream(path_lora, std::ios::binary);
  3071. if (!fin) {
  3072. LLAMA_LOG_ERROR("%s: failed to open '%s'\n", __func__, path_lora);
  3073. return 1;
  3074. }
  3075. // verify magic and version
  3076. {
  3077. uint32_t magic;
  3078. fin.read((char *) &magic, sizeof(magic));
  3079. uint32_t format_version;
  3080. fin.read((char *) &format_version, sizeof(format_version));
  3081. if (format_version != 1) {
  3082. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  3083. return 1;
  3084. }
  3085. }
  3086. int32_t lora_r;
  3087. int32_t lora_alpha;
  3088. fin.read((char *) &lora_r, sizeof(lora_r));
  3089. fin.read((char *) &lora_alpha, sizeof(lora_alpha));
  3090. float scaling = (float)lora_alpha / (float)lora_r;
  3091. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  3092. // create a temporary ggml context to store the lora tensors
  3093. // todo: calculate size from biggest possible tensor
  3094. std::vector<uint8_t> lora_buf(1024ull * 1024ull * 1024ull);
  3095. struct ggml_init_params params;
  3096. params.mem_size = lora_buf.size();
  3097. params.mem_buffer = lora_buf.data();
  3098. params.no_alloc = false;
  3099. ggml_context * lora_ctx = ggml_init(params);
  3100. std::unordered_map<std::string, struct ggml_tensor *> lora_tensors;
  3101. // create a name -> tensor map of the model to accelerate lookups
  3102. std::unordered_map<std::string, struct ggml_tensor*> model_tensors;
  3103. for (const auto & kv : model.tensors_by_name) {
  3104. model_tensors.insert(kv);
  3105. }
  3106. // load base model
  3107. std::unique_ptr<llama_model_loader> model_loader;
  3108. ggml_context * base_ctx = NULL;
  3109. std::vector<uint8_t> base_buf;
  3110. if (path_base_model) {
  3111. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  3112. model_loader.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true));
  3113. size_t ctx_size;
  3114. size_t mmapped_size;
  3115. model_loader->calc_sizes(ctx_size, mmapped_size);
  3116. base_buf.resize(ctx_size);
  3117. ggml_init_params base_params;
  3118. base_params.mem_size = base_buf.size();
  3119. base_params.mem_buffer = base_buf.data();
  3120. base_params.no_alloc = model_loader->use_mmap;
  3121. base_ctx = ggml_init(base_params);
  3122. // maybe this should in llama_model_loader
  3123. if (model_loader->use_mmap) {
  3124. model_loader->mapping.reset(new llama_mmap(&model_loader->file, /* prefetch */ 0, ggml_is_numa()));
  3125. }
  3126. }
  3127. // read tensors and apply
  3128. bool warned = false;
  3129. int n_tensors = 0;
  3130. std::vector<uint8_t> work_buffer;
  3131. while (true) {
  3132. int32_t n_dims;
  3133. int32_t length;
  3134. int32_t ftype;
  3135. fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  3136. fin.read(reinterpret_cast<char *>(&length), sizeof(length));
  3137. fin.read(reinterpret_cast<char *>(&ftype), sizeof(ftype));
  3138. if (fin.eof()) {
  3139. break;
  3140. }
  3141. int32_t ne[2] = { 1, 1 };
  3142. for (int i = 0; i < n_dims; ++i) {
  3143. fin.read(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  3144. }
  3145. std::string name;
  3146. {
  3147. char buf[1024];
  3148. fin.read(buf, length);
  3149. name = std::string(buf, length);
  3150. }
  3151. // check for lora suffix and get the type of tensor
  3152. const std::string lora_suffix = ".lora";
  3153. size_t pos = name.rfind(lora_suffix);
  3154. if (pos == std::string::npos) {
  3155. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  3156. return 1;
  3157. }
  3158. std::string lora_type = name.substr(pos + lora_suffix.length());
  3159. std::string base_name = name;
  3160. base_name.erase(pos);
  3161. // LLAMA_LOG_INFO("%s: %s => %s (lora type %s) \n", __func__, name.c_str(),base_name.c_str(), lora_type.c_str());
  3162. if (model_tensors.find(base_name) == model_tensors.end()) {
  3163. LLAMA_LOG_ERROR("%s: unknown tensor '%s' in lora adapter\n", __func__, name.data());
  3164. return 1;
  3165. }
  3166. // create ggml tensor
  3167. ggml_type wtype;
  3168. switch (ftype) {
  3169. case 0: wtype = GGML_TYPE_F32; break;
  3170. case 1: wtype = GGML_TYPE_F16; break;
  3171. default:
  3172. {
  3173. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  3174. __func__, ftype);
  3175. return false;
  3176. }
  3177. }
  3178. ggml_tensor * lora_tensor;
  3179. if (n_dims == 2) {
  3180. lora_tensor = ggml_new_tensor_2d(lora_ctx, wtype, ne[0], ne[1]);
  3181. }
  3182. else {
  3183. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  3184. return 1;
  3185. }
  3186. ggml_set_name(lora_tensor, "lora_tensor");
  3187. // load tensor data
  3188. size_t offset = fin.tellg();
  3189. size_t tensor_data_size = ggml_nbytes(lora_tensor);
  3190. offset = (offset + 31) & -32;
  3191. fin.seekg(offset);
  3192. fin.read((char*)lora_tensor->data, tensor_data_size);
  3193. lora_tensors[name] = lora_tensor;
  3194. // check if we have both A and B tensors and apply
  3195. if (lora_tensors.find(base_name + ".loraA") != lora_tensors.end() &&
  3196. lora_tensors.find(base_name + ".loraB") != lora_tensors.end()) {
  3197. ggml_tensor * dest_t = model_tensors[base_name];
  3198. offload_func_t offload_func = llama_nop;
  3199. offload_func_t offload_func_force_inplace = llama_nop;
  3200. #ifdef GGML_USE_CUBLAS
  3201. if (dest_t->backend == GGML_BACKEND_GPU || dest_t->backend == GGML_BACKEND_GPU_SPLIT) {
  3202. if (dest_t->type != GGML_TYPE_F16) {
  3203. throw std::runtime_error(format(
  3204. "%s: error: the simultaneous use of LoRAs and GPU acceleration is only supported for f16 models", __func__));
  3205. }
  3206. offload_func = ggml_cuda_assign_buffers;
  3207. offload_func_force_inplace = ggml_cuda_assign_buffers_force_inplace;
  3208. }
  3209. #endif // GGML_USE_CUBLAS
  3210. ggml_tensor * base_t;
  3211. if (model_loader) {
  3212. struct gguf_context * ctx_gguf = model_loader->ctx_gguf;
  3213. // load from base model
  3214. if (gguf_find_tensor(ctx_gguf, base_name.c_str()) < 0) {
  3215. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  3216. return 1;
  3217. }
  3218. // TODO: not tested!! maybe not working!
  3219. base_t = model_loader->create_tensor(base_ctx, base_name, { (uint32_t)dest_t->ne[0], (uint32_t)dest_t->ne[1] }, GGML_BACKEND_CPU);
  3220. model_loader->load_data_for(base_t);
  3221. } else {
  3222. base_t = dest_t;
  3223. }
  3224. if (ggml_is_quantized(base_t->type)) {
  3225. if (!warned) {
  3226. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  3227. "use a f16 or f32 base model with --lora-base\n", __func__);
  3228. warned = true;
  3229. }
  3230. }
  3231. ggml_tensor * loraA = lora_tensors[base_name + ".loraA"];
  3232. GGML_ASSERT(loraA->type == GGML_TYPE_F32);
  3233. ggml_set_name(loraA, "loraA");
  3234. ggml_tensor * loraB = lora_tensors[base_name + ".loraB"];
  3235. GGML_ASSERT(loraB->type == GGML_TYPE_F32);
  3236. ggml_set_name(loraB, "loraB");
  3237. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  3238. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  3239. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  3240. return 1;
  3241. }
  3242. // w = w + BA*s
  3243. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  3244. offload_func(BA);
  3245. ggml_set_name(BA, "BA");
  3246. if (scaling != 1.0f) {
  3247. ggml_tensor * scale_tensor = ggml_new_f32(lora_ctx, scaling);
  3248. ggml_set_name(scale_tensor, "scale_tensor");
  3249. BA = ggml_scale_inplace(lora_ctx, BA, scale_tensor);
  3250. offload_func(BA);
  3251. ggml_set_name(BA, "BA_scaled");
  3252. }
  3253. ggml_tensor * r;
  3254. if (base_t == dest_t) {
  3255. r = ggml_add_inplace(lora_ctx, dest_t, BA);
  3256. offload_func_force_inplace(r);
  3257. ggml_set_name(r, "r_add_inplace");
  3258. }
  3259. else {
  3260. r = ggml_add(lora_ctx, base_t, BA);
  3261. offload_func(r);
  3262. ggml_set_name(r, "r_add");
  3263. r = ggml_cpy(lora_ctx, r, dest_t);
  3264. offload_func(r);
  3265. ggml_set_name(r, "r_cpy");
  3266. }
  3267. struct ggml_cgraph gf = ggml_build_forward(r);
  3268. ggml_graph_compute_helper(work_buffer, &gf, n_threads);
  3269. // we won't need these tensors again, reset the context to save memory
  3270. ggml_free(lora_ctx);
  3271. lora_ctx = ggml_init(params);
  3272. lora_tensors.clear();
  3273. n_tensors++;
  3274. if (n_tensors % 4 == 0) {
  3275. LLAMA_LOG_INFO(".");
  3276. }
  3277. }
  3278. }
  3279. // TODO: this should be in a destructor, it will leak on failure
  3280. ggml_free(lora_ctx);
  3281. if (base_ctx) {
  3282. ggml_free(base_ctx);
  3283. }
  3284. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  3285. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  3286. return 0;
  3287. }
  3288. //
  3289. // interface implementation
  3290. //
  3291. struct llama_context_params llama_context_default_params() {
  3292. struct llama_context_params result = {
  3293. /*.seed =*/ LLAMA_DEFAULT_SEED,
  3294. /*.n_ctx =*/ 512,
  3295. /*.n_batch =*/ 512,
  3296. /*.gpu_layers =*/ 0,
  3297. /*.main_gpu =*/ 0,
  3298. /*.tensor_split =*/ nullptr,
  3299. /*.rope_freq_base =*/ 10000.0f,
  3300. /*.rope_freq_scale =*/ 1.0f,
  3301. /*.progress_callback =*/ nullptr,
  3302. /*.progress_callback_user_data =*/ nullptr,
  3303. /*.low_vram =*/ false,
  3304. /*.mul_mat_q =*/ false,
  3305. /*.f16_kv =*/ true,
  3306. /*.logits_all =*/ false,
  3307. /*.vocab_only =*/ false,
  3308. /*.use_mmap =*/ true,
  3309. /*.use_mlock =*/ false,
  3310. /*.embedding =*/ false,
  3311. };
  3312. return result;
  3313. }
  3314. struct llama_model_quantize_params llama_model_quantize_default_params() {
  3315. struct llama_model_quantize_params result = {
  3316. /*.nthread =*/ 0,
  3317. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  3318. /*.allow_requantize =*/ false,
  3319. /*.quantize_output_tensor =*/ true,
  3320. };
  3321. return result;
  3322. }
  3323. int llama_max_devices(void) {
  3324. return LLAMA_MAX_DEVICES;
  3325. }
  3326. bool llama_mmap_supported(void) {
  3327. return llama_mmap::SUPPORTED;
  3328. }
  3329. bool llama_mlock_supported(void) {
  3330. return llama_mlock::SUPPORTED;
  3331. }
  3332. void llama_backend_init(bool numa) {
  3333. ggml_time_init();
  3334. // needed to initialize f16 tables
  3335. {
  3336. struct ggml_init_params params = { 0, NULL, false };
  3337. struct ggml_context * ctx = ggml_init(params);
  3338. ggml_free(ctx);
  3339. }
  3340. if (numa) {
  3341. ggml_numa_init();
  3342. }
  3343. #ifdef GGML_USE_MPI
  3344. ggml_mpi_backend_init();
  3345. #endif
  3346. }
  3347. void llama_backend_free(void) {
  3348. #ifdef GGML_USE_MPI
  3349. ggml_mpi_backend_free();
  3350. #endif
  3351. }
  3352. int64_t llama_time_us(void) {
  3353. return ggml_time_us();
  3354. }
  3355. struct llama_model * llama_load_model_from_file(
  3356. const char * path_model,
  3357. struct llama_context_params params) {
  3358. ggml_time_init();
  3359. llama_model * model = new llama_model;
  3360. ggml_type memory_type = params.f16_kv ? GGML_TYPE_F16 : GGML_TYPE_F32;
  3361. if (!llama_model_load(path_model, *model, model->vocab, params.n_ctx, params.n_batch, params.n_gpu_layers,
  3362. params.main_gpu, params.tensor_split, params.mul_mat_q, params.rope_freq_base, params.rope_freq_scale,
  3363. params.low_vram, memory_type, params.use_mmap, params.use_mlock, params.vocab_only,
  3364. params.progress_callback, params.progress_callback_user_data)) {
  3365. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  3366. delete model;
  3367. return nullptr;
  3368. }
  3369. return model;
  3370. }
  3371. void llama_free_model(struct llama_model * model) {
  3372. delete model;
  3373. }
  3374. struct llama_context * llama_new_context_with_model(
  3375. struct llama_model * model,
  3376. struct llama_context_params params) {
  3377. if (!model) {
  3378. return nullptr;
  3379. }
  3380. llama_context * ctx = new llama_context(*model);
  3381. if (params.seed == LLAMA_DEFAULT_SEED) {
  3382. params.seed = time(NULL);
  3383. }
  3384. unsigned cur_percentage = 0;
  3385. if (params.progress_callback == NULL) {
  3386. params.progress_callback_user_data = &cur_percentage;
  3387. params.progress_callback = [](float progress, void * ctx) {
  3388. unsigned * cur_percentage_p = (unsigned *) ctx;
  3389. unsigned percentage = (unsigned) (100 * progress);
  3390. while (percentage > *cur_percentage_p) {
  3391. *cur_percentage_p = percentage;
  3392. LLAMA_LOG_INFO(".");
  3393. if (percentage >= 100) {
  3394. LLAMA_LOG_INFO("\n");
  3395. }
  3396. }
  3397. };
  3398. }
  3399. ctx->rng = std::mt19937(params.seed);
  3400. ctx->logits_all = params.logits_all;
  3401. ggml_type memory_type = params.f16_kv ? GGML_TYPE_F16 : GGML_TYPE_F32;
  3402. // reserve memory for context buffers
  3403. if (!params.vocab_only) {
  3404. if (!llama_kv_cache_init(ctx->model.hparams, ctx->kv_self, memory_type, ctx->model.hparams.n_ctx, params.n_gpu_layers)) {
  3405. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  3406. llama_free(ctx);
  3407. return nullptr;
  3408. }
  3409. {
  3410. const size_t memory_size = ggml_nbytes(ctx->kv_self.k) + ggml_nbytes(ctx->kv_self.v);
  3411. LLAMA_LOG_INFO("%s: kv self size = %7.2f MB\n", __func__, memory_size / 1024.0 / 1024.0);
  3412. }
  3413. const auto & hparams = ctx->model.hparams;
  3414. // resized during inference
  3415. if (params.logits_all) {
  3416. ctx->logits.reserve(hparams.n_ctx*hparams.n_vocab);
  3417. } else {
  3418. ctx->logits.reserve(hparams.n_vocab);
  3419. }
  3420. if (params.embedding){
  3421. ctx->embedding.resize(hparams.n_embd);
  3422. }
  3423. {
  3424. static const size_t tensor_alignment = 32;
  3425. // the compute buffer is used to store the tensor and graph structs, while the allocator buffer is used for the tensor data
  3426. ctx->buf_compute.resize(ggml_tensor_overhead()*GGML_MAX_NODES + ggml_graph_overhead());
  3427. // create measure allocator
  3428. ctx->alloc = ggml_allocr_new_measure(tensor_alignment);
  3429. // build worst-case graph
  3430. int n_tokens = std::min((int)hparams.n_ctx, params.n_batch);
  3431. int n_past = hparams.n_ctx - n_tokens;
  3432. llama_token token = llama_token_bos(ctx); // not actually used by llama_build_graph, but required to choose between token and embedding inputs graph
  3433. ggml_cgraph * gf = llama_build_graph(*ctx, &token, NULL, n_tokens, n_past);
  3434. #ifdef GGML_USE_METAL
  3435. if (params.n_gpu_layers > 0) {
  3436. ctx->ctx_metal = ggml_metal_init(1);
  3437. if (!ctx->ctx_metal) {
  3438. LLAMA_LOG_ERROR("%s: ggml_metal_init() failed\n", __func__);
  3439. llama_free(ctx);
  3440. return NULL;
  3441. }
  3442. ggml_metal_graph_find_concurrency(ctx->ctx_metal, gf, false);
  3443. ggml_allocr_set_parse_seq(ctx->alloc, ggml_metal_get_concur_list(ctx->ctx_metal), ggml_metal_if_optimized(ctx->ctx_metal));
  3444. }
  3445. #endif
  3446. // measure memory requirements for the graph
  3447. size_t alloc_size = ggml_allocr_alloc_graph(ctx->alloc, gf) + tensor_alignment;
  3448. LLAMA_LOG_INFO("%s: compute buffer total size = %7.2f MB\n", __func__, (ctx->buf_compute.size + alloc_size) / 1024.0 / 1024.0);
  3449. // recreate allocator with exact memory requirements
  3450. ggml_allocr_free(ctx->alloc);
  3451. ctx->buf_alloc.resize(alloc_size);
  3452. ctx->alloc = ggml_allocr_new(ctx->buf_alloc.data, ctx->buf_alloc.size, tensor_alignment);
  3453. #ifdef GGML_USE_METAL
  3454. if (ctx->ctx_metal) {
  3455. ggml_allocr_set_parse_seq(ctx->alloc, ggml_metal_get_concur_list(ctx->ctx_metal), ggml_metal_if_optimized(ctx->ctx_metal));
  3456. }
  3457. #endif
  3458. #ifdef GGML_USE_CUBLAS
  3459. if (params.low_vram) {
  3460. LLAMA_LOG_INFO("%s: not allocating a VRAM scratch buffer due to low VRAM option\n", __func__);
  3461. ggml_cuda_set_scratch_size(0); // disable scratch
  3462. } else {
  3463. ggml_cuda_set_scratch_size(alloc_size);
  3464. LLAMA_LOG_INFO("%s: VRAM scratch buffer: %.2f MB\n", __func__, alloc_size / 1024.0 / 1024.0);
  3465. }
  3466. #endif
  3467. }
  3468. }
  3469. #ifdef GGML_USE_METAL
  3470. if (params.n_gpu_layers > 0) {
  3471. // this allocates all Metal resources and memory buffers
  3472. void * data_ptr = NULL;
  3473. size_t data_size = 0;
  3474. if (params.use_mmap) {
  3475. data_ptr = ctx->model.mapping->addr;
  3476. data_size = ctx->model.mapping->size;
  3477. } else {
  3478. data_ptr = ggml_get_mem_buffer(ctx->model.ctx);
  3479. data_size = ggml_get_mem_size (ctx->model.ctx);
  3480. }
  3481. const size_t max_size = ggml_get_max_tensor_size(ctx->model.ctx);
  3482. LLAMA_LOG_INFO("%s: max tensor size = %8.2f MB\n", __func__, max_size/1024.0/1024.0);
  3483. #define LLAMA_METAL_CHECK_BUF(result) \
  3484. if (!(result)) { \
  3485. LLAMA_LOG_ERROR("%s: failed to add buffer\n", __func__); \
  3486. llama_free(ctx); \
  3487. return NULL; \
  3488. }
  3489. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "data", data_ptr, data_size, max_size));
  3490. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "eval", ctx->buf_compute.data, ctx->buf_compute.size, 0));
  3491. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "kv", ctx->kv_self.buf.data, ctx->kv_self.buf.size, 0));
  3492. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "alloc", ctx->buf_alloc.data, ctx->buf_alloc.size, 0));
  3493. #undef LLAMA_METAL_CHECK_BUF
  3494. }
  3495. #endif
  3496. #ifdef GGML_USE_MPI
  3497. ctx->ctx_mpi = ggml_mpi_init();
  3498. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  3499. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  3500. const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  3501. while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  3502. llama_backend_free();
  3503. exit(1);
  3504. }
  3505. #endif
  3506. return ctx;
  3507. }
  3508. struct llama_context * llama_init_from_file(
  3509. const char * path_model,
  3510. struct llama_context_params params) {
  3511. struct llama_model * model = llama_load_model_from_file(path_model, params);
  3512. if (!model) {
  3513. return nullptr;
  3514. }
  3515. struct llama_context * ctx = llama_new_context_with_model(model, params);
  3516. ctx->model_owner = true;
  3517. return ctx;
  3518. }
  3519. void llama_free(struct llama_context * ctx) {
  3520. delete ctx;
  3521. }
  3522. int llama_n_vocab(const struct llama_context * ctx) {
  3523. return ctx->model.vocab.id_to_token.size();
  3524. }
  3525. int llama_n_ctx(const struct llama_context * ctx) {
  3526. return ctx->model.hparams.n_ctx;
  3527. }
  3528. int llama_n_embd(const struct llama_context * ctx) {
  3529. return ctx->model.hparams.n_embd;
  3530. }
  3531. int llama_model_n_vocab(const struct llama_model * model) {
  3532. return model->vocab.id_to_token.size();
  3533. }
  3534. int llama_model_n_ctx(const struct llama_model * model) {
  3535. return model->hparams.n_ctx;
  3536. }
  3537. int llama_model_n_embd(const struct llama_model * model) {
  3538. return model->hparams.n_embd;
  3539. }
  3540. int llama_model_type(const struct llama_model * model, char * buf, size_t buf_size) {
  3541. return snprintf(buf, buf_size, "LLaMA %s %s", llama_model_type_name(model->type), llama_model_ftype_name(model->ftype));
  3542. }
  3543. int llama_model_quantize(
  3544. const char * fname_inp,
  3545. const char * fname_out,
  3546. const llama_model_quantize_params * params) {
  3547. try {
  3548. llama_model_quantize_internal(fname_inp, fname_out, params);
  3549. return 0;
  3550. } catch (const std::exception & err) {
  3551. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  3552. return 1;
  3553. }
  3554. }
  3555. int llama_apply_lora_from_file(struct llama_context * ctx, const char * path_lora, const char * path_base_model, int n_threads) {
  3556. try {
  3557. return llama_apply_lora_from_file_internal(ctx->model, path_lora, path_base_model, n_threads);
  3558. } catch (const std::exception & err) {
  3559. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  3560. return 1;
  3561. }
  3562. }
  3563. int llama_model_apply_lora_from_file(const struct llama_model * model, const char * path_lora, const char * path_base_model, int n_threads) {
  3564. try {
  3565. return llama_apply_lora_from_file_internal(*model, path_lora, path_base_model, n_threads);
  3566. } catch (const std::exception & err) {
  3567. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  3568. return 1;
  3569. }
  3570. }
  3571. int llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  3572. return ctx->kv_self.n;
  3573. }
  3574. #define LLAMA_MAX_RNG_STATE (64*1024)
  3575. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  3576. if (seed == LLAMA_DEFAULT_SEED) {
  3577. seed = time(NULL);
  3578. }
  3579. ctx->rng.seed(seed);
  3580. }
  3581. // Returns the *maximum* size of the state
  3582. size_t llama_get_state_size(const struct llama_context * ctx) {
  3583. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  3584. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  3585. const size_t s_rng_size = sizeof(size_t);
  3586. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  3587. const size_t s_logits_capacity = sizeof(size_t);
  3588. const size_t s_logits_size = sizeof(size_t);
  3589. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  3590. const size_t s_embedding_size = sizeof(size_t);
  3591. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  3592. const size_t s_kv_size = sizeof(size_t);
  3593. const size_t s_kv_ntok = sizeof(int);
  3594. const size_t s_kv = ctx->kv_self.buf.size;
  3595. const size_t s_total = (
  3596. + s_rng_size
  3597. + s_rng
  3598. + s_logits_capacity
  3599. + s_logits_size
  3600. + s_logits
  3601. + s_embedding_size
  3602. + s_embedding
  3603. + s_kv_size
  3604. + s_kv_ntok
  3605. + s_kv
  3606. );
  3607. return s_total;
  3608. }
  3609. // llama_context_data
  3610. struct llama_data_context {
  3611. virtual void write(const void * src, size_t size) = 0;
  3612. virtual size_t get_size_written() = 0;
  3613. virtual ~llama_data_context() = default;
  3614. };
  3615. struct llama_data_buffer_context : llama_data_context {
  3616. uint8_t * ptr;
  3617. size_t size_written = 0;
  3618. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  3619. void write(const void * src, size_t size) override {
  3620. memcpy(ptr, src, size);
  3621. ptr += size;
  3622. size_written += size;
  3623. }
  3624. size_t get_size_written() override {
  3625. return size_written;
  3626. }
  3627. };
  3628. struct llama_data_file_context : llama_data_context {
  3629. llama_file * file;
  3630. size_t size_written = 0;
  3631. llama_data_file_context(llama_file * f) : file(f) {}
  3632. void write(const void * src, size_t size) override {
  3633. file->write_raw(src, size);
  3634. size_written += size;
  3635. }
  3636. size_t get_size_written() override {
  3637. return size_written;
  3638. }
  3639. };
  3640. /** copy state data into either a buffer or file depending on the passed in context
  3641. *
  3642. * file context:
  3643. * llama_file file("/path", "wb");
  3644. * llama_data_file_context data_ctx(&file);
  3645. * llama_copy_state_data(ctx, &data_ctx);
  3646. *
  3647. * buffer context:
  3648. * std::vector<uint8_t> buf(max_size, 0);
  3649. * llama_data_buffer_context data_ctx(&buf.data());
  3650. * llama_copy_state_data(ctx, &data_ctx);
  3651. *
  3652. */
  3653. void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  3654. // copy rng
  3655. {
  3656. std::stringstream rng_ss;
  3657. rng_ss << ctx->rng;
  3658. const size_t rng_size = rng_ss.str().size();
  3659. char rng_buf[LLAMA_MAX_RNG_STATE];
  3660. memset(&rng_buf[0], 0, LLAMA_MAX_RNG_STATE);
  3661. memcpy(&rng_buf[0], rng_ss.str().data(), rng_ss.str().size());
  3662. data_ctx->write(&rng_size, sizeof(rng_size));
  3663. data_ctx->write(&rng_buf[0], LLAMA_MAX_RNG_STATE);
  3664. }
  3665. // copy logits
  3666. {
  3667. const size_t logits_cap = ctx->logits.capacity();
  3668. const size_t logits_size = ctx->logits.size();
  3669. data_ctx->write(&logits_cap, sizeof(logits_cap));
  3670. data_ctx->write(&logits_size, sizeof(logits_size));
  3671. if (logits_size) {
  3672. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  3673. }
  3674. // If there is a gap between the size and the capacity, write padding
  3675. size_t padding_size = (logits_cap - logits_size) * sizeof(float);
  3676. if (padding_size > 0) {
  3677. std::vector<uint8_t> padding(padding_size, 0); // Create a buffer filled with zeros
  3678. data_ctx->write(padding.data(), padding_size);
  3679. }
  3680. }
  3681. // copy embeddings
  3682. {
  3683. const size_t embedding_size = ctx->embedding.size();
  3684. data_ctx->write(&embedding_size, sizeof(embedding_size));
  3685. if (embedding_size) {
  3686. data_ctx->write(ctx->embedding.data(), embedding_size * sizeof(float));
  3687. }
  3688. }
  3689. // copy kv cache
  3690. {
  3691. const auto & kv_self = ctx->kv_self;
  3692. const auto & hparams = ctx->model.hparams;
  3693. const int n_layer = hparams.n_layer;
  3694. const int n_embd = hparams.n_embd_gqa();
  3695. const int n_ctx = hparams.n_ctx;
  3696. const size_t kv_size = kv_self.buf.size;
  3697. const int kv_ntok = llama_get_kv_cache_token_count(ctx);
  3698. data_ctx->write(&kv_size, sizeof(kv_size));
  3699. data_ctx->write(&kv_ntok, sizeof(kv_ntok));
  3700. if (kv_size) {
  3701. const size_t elt_size = ggml_element_size(kv_self.k);
  3702. ggml_context * cpy_ctx = ggml_init({ 4096, NULL, /* no_alloc */ true });
  3703. ggml_cgraph gf{};
  3704. ggml_tensor * kout3d = ggml_new_tensor_3d(cpy_ctx, kv_self.k->type, n_embd, kv_ntok, n_layer);
  3705. std::vector<uint8_t> kout3d_data(ggml_nbytes(kout3d), 0);
  3706. kout3d->data = kout3d_data.data();
  3707. ggml_tensor * vout3d = ggml_new_tensor_3d(cpy_ctx, kv_self.v->type, kv_ntok, n_embd, n_layer);
  3708. std::vector<uint8_t> vout3d_data(ggml_nbytes(vout3d), 0);
  3709. vout3d->data = vout3d_data.data();
  3710. ggml_tensor * k3d = ggml_view_3d(cpy_ctx, kv_self.k,
  3711. n_embd, kv_ntok, n_layer,
  3712. elt_size*n_embd, elt_size*n_embd*n_ctx, 0);
  3713. ggml_tensor * v3d = ggml_view_3d(cpy_ctx, kv_self.v,
  3714. kv_ntok, n_embd, n_layer,
  3715. elt_size*n_ctx, elt_size*n_ctx*n_embd, 0);
  3716. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, k3d, kout3d));
  3717. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, v3d, vout3d));
  3718. ggml_graph_compute_helper(ctx->work_buffer, &gf, /*n_threads*/ 1);
  3719. ggml_free(cpy_ctx);
  3720. // our data is now in the kout3d_data and vout3d_data buffers
  3721. // write them to file
  3722. data_ctx->write(kout3d_data.data(), kout3d_data.size());
  3723. data_ctx->write(vout3d_data.data(), vout3d_data.size());
  3724. }
  3725. }
  3726. }
  3727. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  3728. llama_data_buffer_context data_ctx(dst);
  3729. llama_copy_state_data_internal(ctx, &data_ctx);
  3730. return data_ctx.get_size_written();
  3731. }
  3732. // Sets the state reading from the specified source address
  3733. size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src) {
  3734. uint8_t * inp = src;
  3735. // set rng
  3736. {
  3737. size_t rng_size;
  3738. char rng_buf[LLAMA_MAX_RNG_STATE];
  3739. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  3740. memcpy(&rng_buf[0], inp, LLAMA_MAX_RNG_STATE); inp += LLAMA_MAX_RNG_STATE;
  3741. std::stringstream rng_ss;
  3742. rng_ss.str(std::string(&rng_buf[0], rng_size));
  3743. rng_ss >> ctx->rng;
  3744. GGML_ASSERT(rng_ss.fail() == false);
  3745. }
  3746. // set logits
  3747. {
  3748. size_t logits_cap;
  3749. size_t logits_size;
  3750. memcpy(&logits_cap, inp, sizeof(logits_cap)); inp += sizeof(logits_cap);
  3751. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  3752. GGML_ASSERT(ctx->logits.capacity() == logits_cap);
  3753. if (logits_size) {
  3754. ctx->logits.resize(logits_size);
  3755. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  3756. }
  3757. inp += logits_cap * sizeof(float);
  3758. }
  3759. // set embeddings
  3760. {
  3761. size_t embedding_size;
  3762. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  3763. GGML_ASSERT(ctx->embedding.capacity() == embedding_size);
  3764. if (embedding_size) {
  3765. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  3766. inp += embedding_size * sizeof(float);
  3767. }
  3768. }
  3769. // set kv cache
  3770. {
  3771. const auto & kv_self = ctx->kv_self;
  3772. const auto & hparams = ctx->model.hparams;
  3773. const int n_layer = hparams.n_layer;
  3774. const int n_embd = hparams.n_embd_gqa();
  3775. const int n_ctx = hparams.n_ctx;
  3776. size_t kv_size;
  3777. int kv_ntok;
  3778. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  3779. memcpy(&kv_ntok, inp, sizeof(kv_ntok)); inp += sizeof(kv_ntok);
  3780. if (kv_size) {
  3781. GGML_ASSERT(kv_self.buf.size == kv_size);
  3782. const size_t elt_size = ggml_element_size(kv_self.k);
  3783. ggml_context * cpy_ctx = ggml_init({ 4096, NULL, /* no_alloc */ true });
  3784. ggml_cgraph gf{};
  3785. ggml_tensor * kin3d = ggml_new_tensor_3d(cpy_ctx, kv_self.k->type, n_embd, kv_ntok, n_layer);
  3786. kin3d->data = (void *) inp;
  3787. inp += ggml_nbytes(kin3d);
  3788. ggml_tensor * vin3d = ggml_new_tensor_3d(cpy_ctx, kv_self.v->type, kv_ntok, n_embd, n_layer);
  3789. vin3d->data = (void *) inp;
  3790. inp += ggml_nbytes(vin3d);
  3791. ggml_tensor * k3d = ggml_view_3d(cpy_ctx, kv_self.k,
  3792. n_embd, kv_ntok, n_layer,
  3793. elt_size*n_embd, elt_size*n_embd*n_ctx, 0);
  3794. ggml_tensor * v3d = ggml_view_3d(cpy_ctx, kv_self.v,
  3795. kv_ntok, n_embd, n_layer,
  3796. elt_size*n_ctx, elt_size*n_ctx*n_embd, 0);
  3797. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, kin3d, k3d));
  3798. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, vin3d, v3d));
  3799. ggml_graph_compute_helper(ctx->work_buffer, &gf, /*n_threads*/ 1);
  3800. ggml_free(cpy_ctx);
  3801. }
  3802. ctx->kv_self.n = kv_ntok;
  3803. }
  3804. const size_t nread = inp - src;
  3805. const size_t max_size = llama_get_state_size(ctx);
  3806. GGML_ASSERT(nread <= max_size);
  3807. return nread;
  3808. }
  3809. 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) {
  3810. llama_file file(path_session, "rb");
  3811. // sanity checks
  3812. {
  3813. const uint32_t magic = file.read_u32();
  3814. const uint32_t version = file.read_u32();
  3815. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  3816. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  3817. return false;
  3818. }
  3819. llama_hparams session_hparams;
  3820. file.read_raw(&session_hparams, sizeof(llama_hparams));
  3821. if (session_hparams != ctx->model.hparams) {
  3822. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  3823. return false;
  3824. }
  3825. }
  3826. // load the prompt
  3827. {
  3828. const uint32_t n_token_count = file.read_u32();
  3829. if (n_token_count > n_token_capacity) {
  3830. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  3831. return false;
  3832. }
  3833. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  3834. *n_token_count_out = n_token_count;
  3835. }
  3836. // restore the context state
  3837. {
  3838. const size_t n_state_size_cur = file.size - file.tell();
  3839. const size_t n_state_size_max = llama_get_state_size(ctx);
  3840. if (n_state_size_cur > n_state_size_max) {
  3841. 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);
  3842. return false;
  3843. }
  3844. std::vector<uint8_t> state_data(n_state_size_max);
  3845. file.read_raw(state_data.data(), n_state_size_cur);
  3846. llama_set_state_data(ctx, state_data.data());
  3847. }
  3848. return true;
  3849. }
  3850. 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) {
  3851. try {
  3852. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  3853. } catch (const std::exception & err) {
  3854. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  3855. return false;
  3856. }
  3857. }
  3858. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  3859. llama_file file(path_session, "wb");
  3860. file.write_u32(LLAMA_SESSION_MAGIC);
  3861. file.write_u32(LLAMA_SESSION_VERSION);
  3862. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  3863. // save the prompt
  3864. file.write_u32((uint32_t) n_token_count);
  3865. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  3866. // save the context state using stream saving
  3867. llama_data_file_context data_ctx(&file);
  3868. llama_copy_state_data_internal(ctx, &data_ctx);
  3869. return true;
  3870. }
  3871. int llama_eval(
  3872. struct llama_context * ctx,
  3873. const llama_token * tokens,
  3874. int n_tokens,
  3875. int n_past,
  3876. int n_threads) {
  3877. if (!llama_eval_internal(*ctx, tokens, nullptr, n_tokens, n_past, n_threads, nullptr)) {
  3878. LLAMA_LOG_ERROR("%s: failed to eval\n", __func__);
  3879. return 1;
  3880. }
  3881. // get a more accurate load time, upon first eval
  3882. // TODO: fix this
  3883. if (!ctx->has_evaluated_once) {
  3884. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  3885. ctx->has_evaluated_once = true;
  3886. }
  3887. return 0;
  3888. }
  3889. int llama_eval_embd(
  3890. struct llama_context * ctx,
  3891. const float * embd,
  3892. int n_tokens,
  3893. int n_past,
  3894. int n_threads) {
  3895. if (!llama_eval_internal(*ctx, nullptr, embd, n_tokens, n_past, n_threads, nullptr)) {
  3896. LLAMA_LOG_ERROR("%s: failed to eval\n", __func__);
  3897. return 1;
  3898. }
  3899. // get a more accurate load time, upon first eval
  3900. // TODO: fix this
  3901. if (!ctx->has_evaluated_once) {
  3902. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  3903. ctx->has_evaluated_once = true;
  3904. }
  3905. return 0;
  3906. }
  3907. int llama_eval_export(struct llama_context * ctx, const char * fname) {
  3908. const int n_batch = 1;
  3909. const int n_ctx = 512 - n_batch;
  3910. const std::vector<llama_token> tmp(n_batch, llama_token_bos(ctx));
  3911. if (!llama_eval_internal(*ctx, tmp.data(), nullptr, tmp.size(), n_ctx, 1, fname)) {
  3912. LLAMA_LOG_ERROR("%s: failed to eval\n", __func__);
  3913. return 1;
  3914. }
  3915. return 0;
  3916. }
  3917. float * llama_get_logits(struct llama_context * ctx) {
  3918. return ctx->logits.data();
  3919. }
  3920. float * llama_get_embeddings(struct llama_context * ctx) {
  3921. return ctx->embedding.data();
  3922. }
  3923. const char * llama_token_get_text(const struct llama_context * ctx, llama_token token) {
  3924. return ctx->model.vocab.id_to_token[token].text.c_str();
  3925. }
  3926. float llama_token_get_score(const struct llama_context * ctx, llama_token token) {
  3927. return ctx->model.vocab.id_to_token[token].score;
  3928. }
  3929. llama_token_type llama_token_get_type(const struct llama_context * ctx, llama_token token) {
  3930. return ctx->model.vocab.id_to_token[token].type;
  3931. }
  3932. llama_token llama_token_bos(const struct llama_context * ctx) {
  3933. return ctx->model.vocab.special_bos_id;
  3934. }
  3935. llama_token llama_token_eos(const struct llama_context * ctx) {
  3936. return ctx->model.vocab.special_eos_id;
  3937. }
  3938. llama_token llama_token_nl(const struct llama_context * ctx) {
  3939. return ctx->model.vocab.linefeed_id;
  3940. }
  3941. int llama_tokenize(
  3942. struct llama_context * ctx,
  3943. const char * text,
  3944. llama_token * tokens,
  3945. int n_max_tokens,
  3946. bool add_bos) {
  3947. return llama_tokenize_with_model(&ctx->model, text, tokens, n_max_tokens, add_bos);
  3948. }
  3949. int llama_tokenize_bpe(
  3950. struct llama_context * ctx,
  3951. const char * text,
  3952. llama_token * tokens,
  3953. int n_max_tokens,
  3954. bool add_bos) {
  3955. auto res = llama_tokenize_internal(ctx->model.vocab, text, add_bos, false);
  3956. if (n_max_tokens < (int) res.size()) {
  3957. LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  3958. return -((int) res.size());
  3959. }
  3960. for (size_t i = 0; i < res.size(); i++) {
  3961. tokens[i] = res[i];
  3962. }
  3963. return res.size();
  3964. }
  3965. int llama_tokenize_with_model(
  3966. const struct llama_model * model,
  3967. const char * text,
  3968. llama_token * tokens,
  3969. int n_max_tokens,
  3970. bool add_bos) {
  3971. auto escape = llama_vocab_get_type(model->vocab) == LLAMA_VOCAB_TYPE_SPM;
  3972. auto res = llama_tokenize_internal(model->vocab, text, add_bos, escape);
  3973. if (n_max_tokens < (int) res.size()) {
  3974. LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  3975. return -((int) res.size());
  3976. }
  3977. for (size_t i = 0; i < res.size(); i++) {
  3978. tokens[i] = res[i];
  3979. }
  3980. return res.size();
  3981. }
  3982. int llama_token_to_str(const struct llama_context * ctx, llama_token token, char * buf, int length) {
  3983. return llama_token_to_str_with_model(&ctx->model, token, buf, length);
  3984. }
  3985. int llama_token_to_str_bpe(const struct llama_context * ctx, llama_token token, char * buf, int length) {
  3986. if (0 <= token && token < llama_model_n_vocab(&ctx->model)) {
  3987. std::string result = ctx->model.vocab.id_to_token[token].text;
  3988. if (length < (int) result.length()) {
  3989. return -result.length();
  3990. }
  3991. memcpy(buf, result.c_str(), result.length());
  3992. return result.length();
  3993. }
  3994. return 0;
  3995. }
  3996. // does not write null-terminator to str
  3997. int llama_token_to_str_with_model(const struct llama_model * model, llama_token token, char * buf, int length) {
  3998. if (0 <= token && token < llama_model_n_vocab(model)) {
  3999. if (llama_is_normal_token(model->vocab, token)) {
  4000. std::string result = model->vocab.id_to_token[token].text;
  4001. if (llama_vocab_get_type(model->vocab) == LLAMA_VOCAB_TYPE_SPM) {
  4002. result = llama_unescape_whitespace(result);
  4003. }
  4004. if (length < (int) result.length()) {
  4005. return -result.length();
  4006. }
  4007. memcpy(buf, result.c_str(), result.length());
  4008. return result.length();
  4009. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  4010. if (length < 3) {
  4011. return -3;
  4012. }
  4013. buf[0] = '\xe2';
  4014. buf[1] = '\x96';
  4015. buf[2] = '\x85';
  4016. return 3;
  4017. } else if (llama_is_control_token(model->vocab, token)) {
  4018. ;
  4019. } else if (llama_is_byte_token(model->vocab, token)) {
  4020. if (length < 1) {
  4021. return -1;
  4022. }
  4023. buf[0] = llama_token_to_byte(model->vocab, token);
  4024. return 1;
  4025. }
  4026. }
  4027. return 0;
  4028. }
  4029. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  4030. struct llama_timings result = {
  4031. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  4032. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  4033. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  4034. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  4035. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  4036. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  4037. /*.n_sample =*/ std::max(1, ctx->n_sample),
  4038. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  4039. /*.n_eval =*/ std::max(1, ctx->n_eval),
  4040. };
  4041. return result;
  4042. }
  4043. void llama_print_timings(struct llama_context * ctx) {
  4044. const llama_timings timings = llama_get_timings(ctx);
  4045. LLAMA_LOG_INFO("\n");
  4046. LLAMA_LOG_INFO("%s: load time = %8.2f ms\n", __func__, timings.t_load_ms);
  4047. LLAMA_LOG_INFO("%s: sample time = %8.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  4048. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  4049. LLAMA_LOG_INFO("%s: prompt eval time = %8.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  4050. __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);
  4051. LLAMA_LOG_INFO("%s: eval time = %8.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  4052. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  4053. LLAMA_LOG_INFO("%s: total time = %8.2f ms\n", __func__, (timings.t_end_ms - timings.t_start_ms));
  4054. }
  4055. void llama_reset_timings(struct llama_context * ctx) {
  4056. ctx->t_start_us = ggml_time_us();
  4057. ctx->t_sample_us = ctx->n_sample = 0;
  4058. ctx->t_eval_us = ctx->n_eval = 0;
  4059. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  4060. }
  4061. const char * llama_print_system_info(void) {
  4062. static std::string s;
  4063. s = "";
  4064. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  4065. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  4066. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  4067. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  4068. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  4069. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  4070. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  4071. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  4072. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  4073. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  4074. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  4075. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  4076. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  4077. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  4078. return s.c_str();
  4079. }
  4080. // For internal test use
  4081. const std::vector<std::pair<std::string, struct ggml_tensor *>>& llama_internal_get_tensor_map(struct llama_context * ctx) {
  4082. return ctx->model.tensors_by_name;
  4083. }
  4084. void llama_log_set(llama_log_callback log_callback, void * user_data) {
  4085. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  4086. g_state.log_callback_user_data = user_data;
  4087. }
  4088. #if defined(_MSC_VER) && !defined(vsnprintf)
  4089. #define vsnprintf _vsnprintf
  4090. #endif
  4091. static void llama_log_internal_v(llama_log_level level, const char * format, va_list args) {
  4092. va_list args_copy;
  4093. va_copy(args_copy, args);
  4094. char buffer[128];
  4095. int len = vsnprintf(buffer, 128, format, args);
  4096. if (len < 128) {
  4097. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  4098. } else {
  4099. char* buffer2 = new char[len+1];
  4100. vsnprintf(buffer2, len+1, format, args_copy);
  4101. buffer2[len] = 0;
  4102. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  4103. delete[] buffer2;
  4104. }
  4105. va_end(args_copy);
  4106. }
  4107. static void llama_log_internal(llama_log_level level, const char * format, ...) {
  4108. va_list args;
  4109. va_start(args, format);
  4110. llama_log_internal_v(level, format, args);
  4111. va_end(args);
  4112. }
  4113. static void llama_log_callback_default(llama_log_level level, const char * text, void * user_data) {
  4114. (void) level;
  4115. (void) user_data;
  4116. fputs(text, stderr);
  4117. fflush(stderr);
  4118. }