llama.cpp 148 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278
  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-util.h"
  9. #include "llama.h"
  10. #include "ggml.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. #include <array>
  32. #include <ctime>
  33. #include <cinttypes>
  34. #include <fstream>
  35. #include <random>
  36. #include <map>
  37. #include <unordered_map>
  38. #include <queue>
  39. #include <cassert>
  40. #include <cstring>
  41. #include <climits>
  42. #include <memory>
  43. #include <algorithm>
  44. #include <initializer_list>
  45. #include <thread>
  46. #include <atomic>
  47. #include <mutex>
  48. #include <sstream>
  49. #include <numeric>
  50. #if defined(_MSC_VER)
  51. #pragma warning(disable: 4244 4267) // possible loss of data
  52. #endif
  53. #if !defined(GGML_USE_CUBLAS) && !defined(GGML_USE_METAL)
  54. #include "ggml-alloc.h"
  55. #define LLAMA_USE_ALLOCATOR
  56. #else
  57. #define LLAMA_USE_SCRATCH
  58. #define LLAMA_MAX_SCRATCH_BUFFERS 16
  59. #endif
  60. // available llama models
  61. enum e_model {
  62. MODEL_UNKNOWN,
  63. MODEL_3B,
  64. MODEL_7B,
  65. MODEL_13B,
  66. MODEL_30B,
  67. MODEL_65B,
  68. MODEL_70B,
  69. };
  70. static const size_t kB = 1024;
  71. static const size_t MB = 1024*1024;
  72. // computed for n_ctx == 2048
  73. // TODO: dynamically determine these sizes
  74. // needs modifications in ggml
  75. typedef void (*offload_func_t)(struct ggml_tensor * tensor);
  76. void llama_nop(struct ggml_tensor * tensor) { // don't offload by default
  77. (void) tensor;
  78. }
  79. //
  80. // ggml helpers
  81. //
  82. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  83. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  84. if (plan.work_size > 0) {
  85. buf.resize(plan.work_size);
  86. plan.work_data = buf.data();
  87. }
  88. ggml_graph_compute(graph, &plan);
  89. }
  90. //
  91. // memory sizes (calculated for n_batch == 512)
  92. //
  93. static const std::map<e_model, size_t> & MEM_REQ_SCRATCH0(int n_ctx)
  94. {
  95. static std::map<e_model, size_t> k_sizes = {
  96. { MODEL_3B, ((size_t) n_ctx / 16ull + 92ull) * MB },
  97. { MODEL_7B, ((size_t) n_ctx / 16ull + 100ull) * MB },
  98. { MODEL_13B, ((size_t) n_ctx / 12ull + 120ull) * MB },
  99. { MODEL_30B, ((size_t) n_ctx / 9ull + 160ull) * MB },
  100. { MODEL_65B, ((size_t) n_ctx / 6ull + 256ull) * MB }, // guess
  101. { MODEL_70B, ((size_t) n_ctx / 7ull + 164ull) * MB },
  102. };
  103. return k_sizes;
  104. }
  105. static const std::map<e_model, size_t> & MEM_REQ_SCRATCH1()
  106. {
  107. static std::map<e_model, size_t> k_sizes = {
  108. { MODEL_3B, 128ull * MB },
  109. { MODEL_7B, 160ull * MB },
  110. { MODEL_13B, 192ull * MB },
  111. { MODEL_30B, 256ull * MB },
  112. { MODEL_65B, 384ull * MB }, // guess
  113. { MODEL_70B, 304ull * MB },
  114. };
  115. return k_sizes;
  116. }
  117. // used to store the compute graph tensors + non-scratch data
  118. static const std::map<e_model, size_t> & MEM_REQ_EVAL()
  119. {
  120. static std::map<e_model, size_t> k_sizes = {
  121. { MODEL_3B, 8ull * MB },
  122. { MODEL_7B, 10ull * MB },
  123. { MODEL_13B, 12ull * MB },
  124. { MODEL_30B, 16ull * MB },
  125. { MODEL_65B, 24ull * MB }, // guess
  126. { MODEL_70B, 24ull * MB },
  127. };
  128. return k_sizes;
  129. }
  130. // amount of VRAM needed per batch size to hold temporary results
  131. // the values for 3b and 65b are not derived from testing but instead chosen conservatively
  132. static const std::map<e_model, size_t> & VRAM_REQ_SCRATCH_BASE()
  133. {
  134. static std::map<e_model, size_t> k_sizes = {
  135. { MODEL_3B, 512ull * kB },
  136. { MODEL_7B, 512ull * kB },
  137. { MODEL_13B, 640ull * kB },
  138. { MODEL_30B, 768ull * kB },
  139. { MODEL_65B, 1536ull * kB },
  140. { MODEL_70B, 1536ull * kB }, // TODO (likely can be reduced)
  141. };
  142. return k_sizes;
  143. }
  144. // amount of VRAM needed per batch size and context to hold temporary results
  145. // the values for 3b and 65b are not derived from testing but instead chosen conservatively
  146. static const std::map<e_model, size_t> & VRAM_REQ_SCRATCH_PER_CONTEXT()
  147. {
  148. static std::map<e_model, size_t> k_sizes = {
  149. { MODEL_3B, 128ull },
  150. { MODEL_7B, 128ull },
  151. { MODEL_13B, 160ull },
  152. { MODEL_30B, 208ull },
  153. { MODEL_65B, 416ull },
  154. { MODEL_70B, 416ull }, // TODO (likely can be reduced)
  155. };
  156. return k_sizes;
  157. }
  158. // default hparams (LLaMA 7B)
  159. struct llama_hparams {
  160. uint32_t n_vocab = 32000;
  161. uint32_t n_ctx = 512; // this is provided as user input?
  162. uint32_t n_embd = 4096;
  163. uint32_t n_mult = 256;
  164. uint32_t n_head = 32;
  165. uint32_t n_head_kv = 32;
  166. uint32_t n_layer = 32;
  167. uint32_t n_rot = 64;
  168. // LLaMAv2
  169. // TODO: load from model data hparams
  170. float f_ffn_mult = 1.0f;
  171. float f_rms_norm_eps = LLAMA_DEFAULT_RMS_EPS;
  172. float rope_freq_base = 10000.0f;
  173. float rope_freq_scale = 1.0f;
  174. enum llama_ftype ftype = LLAMA_FTYPE_MOSTLY_F16;
  175. bool operator!=(const llama_hparams & other) const {
  176. return static_cast<bool>(memcmp(this, &other, sizeof(llama_hparams))); // NOLINT
  177. }
  178. uint32_t n_gqa() const {
  179. return n_head/n_head_kv;
  180. }
  181. uint32_t n_embd_head() const {
  182. return n_embd/n_head;
  183. }
  184. uint32_t n_embd_gqa() const {
  185. return n_embd/n_gqa();
  186. }
  187. size_t kv_size() const {
  188. size_t result = 2ull;
  189. result *= (size_t) n_embd_gqa();
  190. result *= (size_t) n_ctx;
  191. result *= (size_t) n_layer;
  192. result *= sizeof(ggml_fp16_t);
  193. return result;
  194. }
  195. };
  196. struct llama_layer {
  197. // normalization
  198. struct ggml_tensor * attention_norm;
  199. // attention
  200. struct ggml_tensor * wq;
  201. struct ggml_tensor * wk;
  202. struct ggml_tensor * wv;
  203. struct ggml_tensor * wo;
  204. // normalization
  205. struct ggml_tensor * ffn_norm;
  206. // ff
  207. struct ggml_tensor * w1;
  208. struct ggml_tensor * w2;
  209. struct ggml_tensor * w3;
  210. };
  211. struct llama_kv_cache {
  212. struct ggml_tensor * k = NULL;
  213. struct ggml_tensor * v = NULL;
  214. struct ggml_context * ctx = NULL;
  215. llama_ctx_buffer buf;
  216. int n; // number of tokens currently in the cache
  217. ~llama_kv_cache() {
  218. if (ctx) {
  219. ggml_free(ctx);
  220. }
  221. #ifdef GGML_USE_CUBLAS
  222. ggml_cuda_free_data(k);
  223. ggml_cuda_free_data(v);
  224. #endif // GGML_USE_CUBLAS
  225. }
  226. };
  227. struct llama_vocab {
  228. using id = int32_t;
  229. using token = std::string;
  230. struct token_score {
  231. token tok;
  232. float score;
  233. };
  234. std::unordered_map<token, id> token_to_id;
  235. std::vector<token_score> id_to_token;
  236. };
  237. struct llama_model {
  238. e_model type = MODEL_UNKNOWN;
  239. llama_hparams hparams;
  240. struct ggml_tensor * tok_embeddings;
  241. struct ggml_tensor * norm;
  242. struct ggml_tensor * output;
  243. std::vector<llama_layer> layers;
  244. int n_gpu_layers;
  245. // context
  246. struct ggml_context * ctx = NULL;
  247. // the model memory buffer
  248. llama_ctx_buffer buf;
  249. // model memory mapped file
  250. std::unique_ptr<llama_mmap> mapping;
  251. // objects representing data potentially being locked in memory
  252. llama_mlock mlock_buf;
  253. llama_mlock mlock_mmap;
  254. // for quantize-stats only
  255. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  256. int64_t t_load_us = 0;
  257. int64_t t_start_us = 0;
  258. llama_vocab vocab;
  259. ~llama_model() {
  260. if (ctx) {
  261. ggml_free(ctx);
  262. }
  263. #ifdef GGML_USE_CUBLAS
  264. for (size_t i = 0; i < tensors_by_name.size(); ++i) {
  265. ggml_cuda_free_data(tensors_by_name[i].second);
  266. }
  267. ggml_cuda_free_scratch();
  268. #elif defined(GGML_USE_CLBLAST)
  269. for (size_t i = 0; i < tensors_by_name.size(); ++i) {
  270. ggml_cl_free_data(tensors_by_name[i].second);
  271. }
  272. #endif
  273. }
  274. };
  275. struct llama_context {
  276. llama_context(const llama_model & model) : model(model), t_load_us(model.t_load_us), t_start_us(model.t_start_us) {}
  277. ~llama_context() {
  278. if (model_owner) {
  279. delete &model;
  280. }
  281. #ifdef GGML_USE_METAL
  282. if (ctx_metal) {
  283. ggml_metal_free(ctx_metal);
  284. }
  285. #endif
  286. #ifdef LLAMA_USE_ALLOCATOR
  287. if (alloc) {
  288. ggml_allocr_free(alloc);
  289. }
  290. #endif
  291. }
  292. std::mt19937 rng;
  293. bool has_evaluated_once = false;
  294. int64_t t_sample_us = 0;
  295. int64_t t_eval_us = 0;
  296. int64_t t_p_eval_us = 0;
  297. int32_t n_sample = 0; // number of tokens sampled
  298. int32_t n_eval = 0; // number of eval calls
  299. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  300. const llama_model & model;
  301. bool model_owner = false;
  302. int64_t t_load_us;
  303. int64_t t_start_us;
  304. // key + value cache for the self attention
  305. struct llama_kv_cache kv_self;
  306. size_t mem_per_token = 0;
  307. // decode output (2-dimensional array: [n_tokens][n_vocab])
  308. std::vector<float> logits;
  309. bool logits_all = false;
  310. // input embedding (1-dimensional array: [n_embd])
  311. std::vector<float> embedding;
  312. // reusable buffer for `struct ggml_graph_plan.work_data`
  313. std::vector<uint8_t> work_buffer;
  314. // memory buffers used to evaluate the model
  315. // TODO: move in llama_state
  316. llama_ctx_buffer buf_compute;
  317. #ifdef LLAMA_USE_ALLOCATOR
  318. llama_ctx_buffer buf_alloc;
  319. ggml_allocr * alloc = NULL;
  320. #endif
  321. #ifdef LLAMA_USE_SCRATCH
  322. llama_ctx_buffer buf_scratch[LLAMA_MAX_SCRATCH_BUFFERS];
  323. int buf_last = 0;
  324. size_t buf_max_size[LLAMA_MAX_SCRATCH_BUFFERS] = { 0 };
  325. #endif
  326. #ifdef GGML_USE_METAL
  327. ggml_metal_context * ctx_metal = NULL;
  328. #endif
  329. #ifdef GGML_USE_MPI
  330. ggml_mpi_context * ctx_mpi = NULL;
  331. #endif
  332. void use_buf(struct ggml_context * ctx, int i) {
  333. #if defined(LLAMA_USE_SCRATCH)
  334. size_t last_size = 0;
  335. if (i == -1) {
  336. last_size = ggml_set_scratch(ctx, { 0, 0, nullptr, });
  337. } else {
  338. auto & buf = buf_scratch[i];
  339. last_size = ggml_set_scratch(ctx, { 0, buf.size, buf.addr, });
  340. }
  341. if (buf_last >= 0) {
  342. buf_max_size[buf_last] = std::max(buf_max_size[buf_last], last_size);
  343. }
  344. buf_last = i;
  345. #else
  346. (void) i;
  347. (void) ctx;
  348. #endif
  349. }
  350. size_t get_buf_max_mem(int i) const {
  351. #if defined(LLAMA_USE_SCRATCH)
  352. return buf_max_size[i];
  353. #else
  354. (void) i;
  355. return 0;
  356. #endif
  357. }
  358. };
  359. template <typename T>
  360. static T checked_mul(T a, T b) {
  361. T ret = a * b;
  362. if (a != 0 && ret / a != b) {
  363. throw std::runtime_error(format("overflow multiplying %llu * %llu",
  364. (unsigned long long) a, (unsigned long long) b));
  365. }
  366. return ret;
  367. }
  368. static size_t checked_div(size_t a, size_t b) {
  369. if (b == 0 || a % b != 0) {
  370. throw std::runtime_error(format("error dividing %zu / %zu", a, b));
  371. }
  372. return a / b;
  373. }
  374. static std::string llama_format_tensor_shape(const std::vector<uint32_t> & ne) {
  375. char buf[256];
  376. snprintf(buf, sizeof(buf), "%5u", ne.at(0));
  377. for (size_t i = 1; i < ne.size(); i++) {
  378. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " x %5u", ne.at(i));
  379. }
  380. return buf;
  381. }
  382. static size_t llama_calc_tensor_size(const std::vector<uint32_t> & ne, enum ggml_type type) {
  383. size_t size = ggml_type_size(type);
  384. for (uint32_t dim : ne) {
  385. size = checked_mul<size_t>(size, dim);
  386. }
  387. return size / ggml_blck_size(type);
  388. }
  389. struct llama_load_tensor {
  390. std::string name;
  391. enum ggml_type type = GGML_TYPE_F32;
  392. std::vector<uint32_t> ne;
  393. size_t file_off;
  394. size_t size;
  395. struct ggml_tensor * ggml_tensor = NULL;
  396. uint8_t * data;
  397. };
  398. struct llama_load_tensors_map {
  399. // tensors is kept in a separate vector to preserve file order
  400. std::vector<llama_load_tensor> tensors;
  401. std::unordered_map<std::string, size_t> name_to_idx;
  402. };
  403. enum llama_file_version {
  404. LLAMA_FILE_VERSION_GGML,
  405. LLAMA_FILE_VERSION_GGMF_V1, // added version field and scores in vocab
  406. LLAMA_FILE_VERSION_GGJT_V1, // added padding
  407. LLAMA_FILE_VERSION_GGJT_V2, // changed quantization format
  408. LLAMA_FILE_VERSION_GGJT_V3, // changed Q4 and Q8 quantization format
  409. };
  410. struct llama_file_loader {
  411. llama_file file;
  412. llama_file_version file_version;
  413. llama_hparams hparams;
  414. llama_vocab vocab;
  415. llama_file_loader(const char * fname, llama_load_tensors_map & tensors_map)
  416. : file(fname, "rb") {
  417. fprintf(stderr, "llama.cpp: loading model from %s\n", fname);
  418. read_magic();
  419. read_hparams();
  420. read_vocab();
  421. read_tensor_metadata(tensors_map);
  422. }
  423. void read_magic() {
  424. uint32_t magic = file.read_u32();
  425. if (magic == LLAMA_FILE_MAGIC_GGML) {
  426. file_version = LLAMA_FILE_VERSION_GGML;
  427. return;
  428. }
  429. uint32_t version = file.read_u32();
  430. switch (magic) {
  431. case LLAMA_FILE_MAGIC_GGMF:
  432. switch (version) {
  433. case 1: file_version = LLAMA_FILE_VERSION_GGMF_V1; return;
  434. }
  435. break;
  436. case LLAMA_FILE_MAGIC_GGJT:
  437. switch (version) {
  438. case 1: file_version = LLAMA_FILE_VERSION_GGJT_V1; return;
  439. case 2: file_version = LLAMA_FILE_VERSION_GGJT_V2; return;
  440. case 3: file_version = LLAMA_FILE_VERSION_GGJT_V3; return;
  441. }
  442. }
  443. throw std::runtime_error(format("unknown (magic, version) combination: %08x, %08x; is this really a GGML file?",
  444. magic, version));
  445. }
  446. void read_hparams() {
  447. hparams.n_vocab = file.read_u32();
  448. hparams.n_embd = file.read_u32();
  449. hparams.n_mult = file.read_u32();
  450. hparams.n_head = file.read_u32();
  451. hparams.n_layer = file.read_u32();
  452. hparams.n_rot = file.read_u32();
  453. hparams.ftype = (enum llama_ftype) file.read_u32();
  454. // LLaMAv2
  455. // TODO: read from header
  456. hparams.n_head_kv = hparams.n_head;
  457. }
  458. void read_vocab() {
  459. vocab.id_to_token.resize(hparams.n_vocab);
  460. for (uint32_t i = 0; i < hparams.n_vocab; i++) {
  461. uint32_t len = file.read_u32();
  462. std::string word = file.read_string(len);
  463. float score = 0.0f;
  464. file.read_raw(&score, sizeof(score));
  465. vocab.token_to_id[word] = i;
  466. auto & tok_score = vocab.id_to_token[i];
  467. tok_score.tok = std::move(word);
  468. tok_score.score = score;
  469. }
  470. }
  471. void read_tensor_metadata(llama_load_tensors_map & tensors_map) {
  472. while (file.tell() < file.size) {
  473. llama_load_tensor tensor;
  474. uint32_t n_dims = file.read_u32();
  475. uint32_t name_len = file.read_u32();
  476. tensor.type = (enum ggml_type) file.read_u32();
  477. tensor.ne.resize(n_dims);
  478. file.read_raw(tensor.ne.data(), sizeof(tensor.ne[0]) * n_dims);
  479. std::string name = file.read_string(name_len);
  480. if (n_dims < 1 || n_dims > 2) {
  481. throw std::runtime_error(format("llama.cpp: tensor '%s' should not be %u-dimensional", name.c_str(), n_dims));
  482. }
  483. switch (tensor.type) {
  484. case GGML_TYPE_F32:
  485. case GGML_TYPE_F16:
  486. case GGML_TYPE_Q4_0:
  487. case GGML_TYPE_Q4_1:
  488. case GGML_TYPE_Q5_0:
  489. case GGML_TYPE_Q5_1:
  490. case GGML_TYPE_Q8_0:
  491. case GGML_TYPE_Q2_K:
  492. case GGML_TYPE_Q3_K:
  493. case GGML_TYPE_Q4_K:
  494. case GGML_TYPE_Q5_K:
  495. case GGML_TYPE_Q6_K:
  496. break;
  497. default: {
  498. throw std::runtime_error(format("unrecognized tensor type %u\n", tensor.type));
  499. }
  500. }
  501. // skip to the next multiple of 32 bytes
  502. if (file_version >= LLAMA_FILE_VERSION_GGJT_V1) {
  503. file.seek(-static_cast<ptrdiff_t>(file.tell()) & 31, SEEK_CUR);
  504. }
  505. tensor.file_off = file.tell();
  506. tensor.name = name;
  507. tensor.size = llama_calc_tensor_size(tensor.ne, tensor.type);
  508. file.seek(tensor.size, SEEK_CUR);
  509. tensors_map.tensors.push_back(tensor);
  510. tensors_map.name_to_idx[name] = tensors_map.tensors.size() - 1;
  511. }
  512. }
  513. };
  514. struct llama_file_saver {
  515. llama_file file;
  516. llama_file_loader * any_file_loader;
  517. llama_file_saver(const char * fname, llama_file_loader * any_file_loader, enum llama_ftype new_ftype)
  518. : file(fname, "wb"), any_file_loader(any_file_loader) {
  519. fprintf(stderr, "llama.cpp: saving model to %s\n", fname);
  520. write_magic();
  521. write_hparams(new_ftype);
  522. write_vocab();
  523. }
  524. void write_magic() {
  525. file.write_u32(LLAMA_FILE_MAGIC); // magic
  526. file.write_u32(LLAMA_FILE_VERSION); // version
  527. }
  528. void write_hparams(enum llama_ftype new_ftype) {
  529. const llama_hparams & hparams = any_file_loader->hparams;
  530. file.write_u32(hparams.n_vocab);
  531. file.write_u32(hparams.n_embd);
  532. file.write_u32(hparams.n_mult);
  533. file.write_u32(hparams.n_head);
  534. file.write_u32(hparams.n_layer);
  535. file.write_u32(hparams.n_rot);
  536. file.write_u32(new_ftype);
  537. }
  538. void write_vocab() {
  539. if (any_file_loader->file_version == LLAMA_FILE_VERSION_GGML) {
  540. fprintf(stderr, "llama.cpp: WARNING: input is an old file that doesn't have scores; will add dummy scores\n");
  541. }
  542. uint32_t n_vocab = any_file_loader->hparams.n_vocab;
  543. for (uint32_t i = 0; i < n_vocab; i++) {
  544. const auto & token_score = any_file_loader->vocab.id_to_token.at(i);
  545. file.write_u32((uint32_t) token_score.tok.size());
  546. file.write_raw(token_score.tok.data(), token_score.tok.size());
  547. file.write_raw(&token_score.score, sizeof(token_score.score));
  548. }
  549. }
  550. void write_tensor(llama_load_tensor & tensor, enum ggml_type new_type, const void * new_data, size_t new_size) {
  551. switch (new_type) {
  552. case GGML_TYPE_F32:
  553. case GGML_TYPE_F16:
  554. case GGML_TYPE_Q4_0:
  555. case GGML_TYPE_Q4_1:
  556. case GGML_TYPE_Q5_0:
  557. case GGML_TYPE_Q5_1:
  558. case GGML_TYPE_Q8_0:
  559. case GGML_TYPE_Q2_K:
  560. case GGML_TYPE_Q3_K:
  561. case GGML_TYPE_Q4_K:
  562. case GGML_TYPE_Q5_K:
  563. case GGML_TYPE_Q6_K:
  564. break;
  565. default: LLAMA_ASSERT(false);
  566. }
  567. file.write_u32((uint32_t) tensor.ne.size());
  568. file.write_u32((uint32_t) tensor.name.size());
  569. file.write_u32(new_type);
  570. file.write_raw(tensor.ne.data(), sizeof(tensor.ne[0]) * tensor.ne.size());
  571. file.write_raw(tensor.name.data(), tensor.name.size());
  572. file.seek(-static_cast<ptrdiff_t>(file.tell()) & 31, SEEK_CUR);
  573. LLAMA_ASSERT(new_size == llama_calc_tensor_size(tensor.ne, new_type));
  574. file.write_raw(new_data, new_size);
  575. }
  576. };
  577. struct llama_model_loader {
  578. std::unique_ptr<llama_file_loader> file_loader;
  579. llama_load_tensors_map tensors_map;
  580. bool use_mmap;
  581. size_t num_ggml_tensors_created = 0;
  582. struct ggml_context * ggml_ctx = NULL;
  583. std::unique_ptr<llama_mmap> mapping;
  584. llama_model_loader(const std::string & fname_base, bool use_mmap) {
  585. file_loader = std::unique_ptr<llama_file_loader>(new llama_file_loader(fname_base.c_str(), tensors_map));
  586. if (!llama_mmap::SUPPORTED) {
  587. use_mmap = false;
  588. }
  589. this->use_mmap = use_mmap;
  590. }
  591. void calc_sizes(size_t * ctx_size_p, size_t * mmapped_size_p) const {
  592. *ctx_size_p = *mmapped_size_p = 0;
  593. for (const llama_load_tensor & lt : tensors_map.tensors) {
  594. *ctx_size_p += sizeof(struct ggml_tensor) + GGML_OBJECT_SIZE;
  595. *(use_mmap ? mmapped_size_p : ctx_size_p) += lt.size + 16;
  596. }
  597. }
  598. struct ggml_tensor * get_tensor(const std::string & name, const std::vector<uint32_t> & ne, ggml_backend backend) {
  599. auto it = tensors_map.name_to_idx.find(name);
  600. if (it == tensors_map.name_to_idx.end()) {
  601. throw std::runtime_error(std::runtime_error(format("llama.cpp: tensor '%s' is missing from model", name.c_str())));
  602. }
  603. llama_load_tensor & lt = tensors_map.tensors.at(it->second);
  604. if (lt.ne != ne) {
  605. throw std::runtime_error(format("llama.cpp: tensor '%s' has wrong shape; expected %s, got %s",
  606. name.c_str(), llama_format_tensor_shape(ne).c_str(), llama_format_tensor_shape(lt.ne).c_str()));
  607. }
  608. return get_tensor_for(lt, backend);
  609. }
  610. struct ggml_tensor * get_tensor_for(llama_load_tensor & lt, ggml_backend backend) {
  611. struct ggml_tensor * tensor;
  612. if (backend != GGML_BACKEND_CPU) {
  613. ggml_set_no_alloc(ggml_ctx, true);
  614. }
  615. if (lt.ne.size() == 2) {
  616. tensor = ggml_new_tensor_2d(ggml_ctx, lt.type, lt.ne.at(0), lt.ne.at(1));
  617. } else {
  618. LLAMA_ASSERT(lt.ne.size() == 1);
  619. tensor = ggml_new_tensor_1d(ggml_ctx, lt.type, lt.ne.at(0));
  620. }
  621. ggml_set_name(tensor, lt.name.c_str());
  622. LLAMA_ASSERT(lt.ggml_tensor == NULL); // if this fails, we called get_tensor twice on the same tensor
  623. if (backend != GGML_BACKEND_CPU) {
  624. ggml_set_no_alloc(ggml_ctx, use_mmap);
  625. }
  626. tensor->backend = backend;
  627. lt.ggml_tensor = tensor;
  628. num_ggml_tensors_created++;
  629. return tensor;
  630. }
  631. void done_getting_tensors() const {
  632. if (num_ggml_tensors_created != tensors_map.tensors.size()) {
  633. throw std::runtime_error(std::string("llama.cpp: file contained more tensors than expected"));
  634. }
  635. }
  636. void load_all_data(llama_progress_callback progress_callback, void * progress_callback_user_data, llama_mlock * lmlock) {
  637. size_t data_size = 0;
  638. size_t prefetch_size = file_loader->file.size;
  639. size_t lock_size = 0;
  640. for (const llama_load_tensor & lt : tensors_map.tensors) {
  641. data_size += lt.size;
  642. if (lt.ggml_tensor->backend != GGML_BACKEND_CPU) {
  643. prefetch_size -= lt.size;
  644. }
  645. }
  646. if (use_mmap) {
  647. mapping.reset(new llama_mmap(&file_loader->file, prefetch_size, ggml_is_numa()));
  648. if (lmlock) {
  649. lmlock->init(mapping->addr);
  650. }
  651. }
  652. size_t done_size = 0;
  653. for (llama_load_tensor & lt : tensors_map.tensors) {
  654. if (progress_callback) {
  655. progress_callback((float) done_size / data_size, progress_callback_user_data);
  656. }
  657. LLAMA_ASSERT(lt.ggml_tensor); // unused tensors should have been caught by load_data already
  658. lt.data = (uint8_t *) lt.ggml_tensor->data;
  659. // allocate temp buffer if not using mmap
  660. if (!use_mmap && lt.data == NULL) {
  661. GGML_ASSERT(lt.ggml_tensor->backend != GGML_BACKEND_CPU);
  662. lt.data = (uint8_t*)malloc(ggml_nbytes(lt.ggml_tensor));
  663. }
  664. load_data_for(lt);
  665. switch(lt.ggml_tensor->backend) {
  666. case GGML_BACKEND_CPU:
  667. lt.ggml_tensor->data = lt.data;
  668. if (use_mmap && lmlock) {
  669. lock_size += lt.size;
  670. lmlock->grow_to(lock_size);
  671. }
  672. break;
  673. #if defined(GGML_USE_CUBLAS)
  674. case GGML_BACKEND_GPU:
  675. case GGML_BACKEND_GPU_SPLIT:
  676. ggml_cuda_transform_tensor(lt.data, lt.ggml_tensor);
  677. if (!use_mmap) {
  678. free(lt.data);
  679. }
  680. break;
  681. #elif defined(GGML_USE_CLBLAST)
  682. case GGML_BACKEND_GPU:
  683. ggml_cl_transform_tensor(lt.data, lt.ggml_tensor);
  684. if (!use_mmap) {
  685. free(lt.data);
  686. }
  687. break;
  688. #endif
  689. default:
  690. continue;
  691. }
  692. done_size += lt.size;
  693. }
  694. }
  695. void load_data_for(llama_load_tensor & lt) {
  696. if (use_mmap) {
  697. lt.data = (uint8_t *) mapping->addr + lt.file_off;
  698. } else {
  699. llama_file & file = file_loader->file;
  700. file.seek(lt.file_off, SEEK_SET);
  701. file.read_raw(lt.data, lt.size);
  702. }
  703. if (0) {
  704. print_checksum(lt);
  705. }
  706. }
  707. static void print_checksum(llama_load_tensor & lt) {
  708. uint32_t sum = 0;
  709. for (size_t i = 0; i < lt.size; i++) {
  710. uint8_t byte = lt.data[i];
  711. sum = byte + (sum << 6) + (sum << 16) - sum; // sdbm hash
  712. }
  713. fprintf(stderr, "%s checksum: %#08x (%s, size %zu)\n", lt.name.c_str(), sum,
  714. llama_format_tensor_shape(lt.ne).c_str(), lt.size);
  715. }
  716. };
  717. //
  718. // kv cache
  719. //
  720. static bool kv_cache_init(
  721. const struct llama_hparams & hparams,
  722. struct llama_kv_cache & cache,
  723. ggml_type wtype,
  724. int n_ctx,
  725. int n_gpu_layers) {
  726. const int n_embd = hparams.n_embd_gqa();
  727. const int n_layer = hparams.n_layer;
  728. const int64_t n_mem = n_layer*n_ctx;
  729. const int64_t n_elements = n_embd*n_mem;
  730. cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
  731. cache.n = 0;
  732. struct ggml_init_params params;
  733. params.mem_size = cache.buf.size;
  734. params.mem_buffer = cache.buf.addr;
  735. params.no_alloc = false;
  736. cache.ctx = ggml_init(params);
  737. if (!cache.ctx) {
  738. fprintf(stderr, "%s: failed to allocate memory for kv cache\n", __func__);
  739. return false;
  740. }
  741. cache.k = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  742. cache.v = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  743. ggml_set_name(cache.k, "cache_k");
  744. ggml_set_name(cache.v, "cache_v");
  745. (void) n_gpu_layers;
  746. #ifdef GGML_USE_CUBLAS
  747. if (n_gpu_layers > n_layer + 1) {
  748. ggml_cuda_assign_buffers_no_scratch(cache.v);
  749. }
  750. if (n_gpu_layers > n_layer + 2) {
  751. ggml_cuda_assign_buffers_no_scratch(cache.k);
  752. }
  753. #endif // GGML_USE_CUBLAS
  754. return true;
  755. }
  756. struct llama_context_params llama_context_default_params() {
  757. struct llama_context_params result = {
  758. /*.seed =*/ LLAMA_DEFAULT_SEED,
  759. /*.n_ctx =*/ 512,
  760. /*.n_batch =*/ 512,
  761. /*.n_gqa =*/ 1,
  762. /*.rms_norm_eps =*/ LLAMA_DEFAULT_RMS_EPS,
  763. /*.gpu_layers =*/ 0,
  764. /*.main_gpu =*/ 0,
  765. /*.tensor_split =*/ nullptr,
  766. /*.rope_freq_base =*/ 10000.0f,
  767. /*.rope_freq_scale =*/ 1.0f,
  768. /*.progress_callback =*/ nullptr,
  769. /*.progress_callback_user_data =*/ nullptr,
  770. /*.low_vram =*/ false,
  771. /*.mul_mat_q =*/ false,
  772. /*.f16_kv =*/ true,
  773. /*.logits_all =*/ false,
  774. /*.vocab_only =*/ false,
  775. /*.use_mmap =*/ true,
  776. /*.use_mlock =*/ false,
  777. /*.embedding =*/ false,
  778. };
  779. return result;
  780. }
  781. struct llama_model_quantize_params llama_model_quantize_default_params() {
  782. struct llama_model_quantize_params result = {
  783. /*.nthread =*/ 0,
  784. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  785. /*.allow_requantize =*/ false,
  786. /*.quantize_output_tensor =*/ true,
  787. };
  788. return result;
  789. }
  790. int llama_max_devices() {
  791. return LLAMA_MAX_DEVICES;
  792. }
  793. bool llama_mmap_supported() {
  794. return llama_mmap::SUPPORTED;
  795. }
  796. bool llama_mlock_supported() {
  797. return llama_mlock::SUPPORTED;
  798. }
  799. void llama_backend_init(bool numa) {
  800. ggml_time_init();
  801. // needed to initialize f16 tables
  802. {
  803. struct ggml_init_params params = { 0, NULL, false };
  804. struct ggml_context * ctx = ggml_init(params);
  805. ggml_free(ctx);
  806. }
  807. if (numa) {
  808. ggml_numa_init();
  809. }
  810. #ifdef GGML_USE_MPI
  811. ggml_mpi_backend_init();
  812. #endif
  813. }
  814. void llama_backend_free() {
  815. #ifdef GGML_USE_MPI
  816. ggml_mpi_backend_free();
  817. #endif
  818. }
  819. int64_t llama_time_us() {
  820. return ggml_time_us();
  821. }
  822. //
  823. // model loading
  824. //
  825. static const char *llama_file_version_name(llama_file_version version) {
  826. switch (version) {
  827. case LLAMA_FILE_VERSION_GGML: return "'ggml' (old version with low tokenizer quality and no mmap support)";
  828. case LLAMA_FILE_VERSION_GGMF_V1: return "ggmf v1 (old version with no mmap support)";
  829. case LLAMA_FILE_VERSION_GGJT_V1: return "ggjt v1 (pre #1405)";
  830. case LLAMA_FILE_VERSION_GGJT_V2: return "ggjt v2 (pre #1508)";
  831. case LLAMA_FILE_VERSION_GGJT_V3: return "ggjt v3 (latest)";
  832. }
  833. return "unknown";
  834. }
  835. static const char *llama_ftype_name(enum llama_ftype ftype) {
  836. switch (ftype) {
  837. case LLAMA_FTYPE_ALL_F32: return "all F32";
  838. case LLAMA_FTYPE_MOSTLY_F16: return "mostly F16";
  839. case LLAMA_FTYPE_MOSTLY_Q4_0: return "mostly Q4_0";
  840. case LLAMA_FTYPE_MOSTLY_Q4_1: return "mostly Q4_1";
  841. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  842. return "mostly Q4_1, some F16";
  843. case LLAMA_FTYPE_MOSTLY_Q5_0: return "mostly Q5_0";
  844. case LLAMA_FTYPE_MOSTLY_Q5_1: return "mostly Q5_1";
  845. case LLAMA_FTYPE_MOSTLY_Q8_0: return "mostly Q8_0";
  846. // K-quants
  847. case LLAMA_FTYPE_MOSTLY_Q2_K: return "mostly Q2_K";
  848. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "mostly Q3_K - Small";
  849. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "mostly Q3_K - Medium";
  850. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "mostly Q3_K - Large";
  851. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "mostly Q4_K - Small";
  852. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "mostly Q4_K - Medium";
  853. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "mostly Q5_K - Small";
  854. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "mostly Q5_K - Medium";
  855. case LLAMA_FTYPE_MOSTLY_Q6_K: return "mostly Q6_K";
  856. default: return "unknown, may not work";
  857. }
  858. }
  859. static const char *llama_model_type_name(e_model type) {
  860. switch (type) {
  861. case MODEL_3B: return "3B";
  862. case MODEL_7B: return "7B";
  863. case MODEL_13B: return "13B";
  864. case MODEL_30B: return "30B";
  865. case MODEL_65B: return "65B";
  866. case MODEL_70B: return "70B";
  867. default: LLAMA_ASSERT(false);
  868. }
  869. }
  870. static void llama_model_load_internal(
  871. const std::string & fname,
  872. llama_model & model,
  873. llama_vocab & vocab,
  874. int n_ctx,
  875. int n_batch,
  876. int n_gqa,
  877. float rms_norm_eps,
  878. int n_gpu_layers,
  879. int main_gpu,
  880. const float * tensor_split,
  881. const bool mul_mat_q,
  882. float rope_freq_base,
  883. float rope_freq_scale,
  884. bool low_vram,
  885. ggml_type memory_type,
  886. bool use_mmap,
  887. bool use_mlock,
  888. bool vocab_only,
  889. llama_progress_callback progress_callback,
  890. void * progress_callback_user_data) {
  891. model.t_start_us = ggml_time_us();
  892. std::unique_ptr<llama_model_loader> ml(new llama_model_loader(fname, use_mmap));
  893. vocab = std::move(ml->file_loader->vocab);
  894. model.hparams = ml->file_loader->hparams;
  895. model.n_gpu_layers = n_gpu_layers;
  896. llama_file_version file_version = ml->file_loader->file_version;
  897. auto & hparams = model.hparams;
  898. // TODO: read from file
  899. hparams.f_rms_norm_eps = rms_norm_eps;
  900. {
  901. switch (hparams.n_layer) {
  902. case 26: model.type = e_model::MODEL_3B; break;
  903. case 32: model.type = e_model::MODEL_7B; break;
  904. case 40: model.type = e_model::MODEL_13B; break;
  905. case 60: model.type = e_model::MODEL_30B; break;
  906. case 80: model.type = e_model::MODEL_65B; break;
  907. default:
  908. {
  909. if (hparams.n_layer < 32) {
  910. model.type = e_model::MODEL_7B;
  911. }
  912. } break;
  913. }
  914. hparams.n_ctx = n_ctx;
  915. // LLaMAv2
  916. // TODO: temporary until GGUF
  917. LLAMA_ASSERT(hparams.n_head % n_gqa == 0);
  918. hparams.n_head_kv = hparams.n_head / n_gqa;
  919. if (model.type == e_model::MODEL_65B && n_gqa == 8) {
  920. fprintf(stderr, "%s: warning: assuming 70B model based on GQA == %d\n", __func__, n_gqa);
  921. model.type = e_model::MODEL_70B;
  922. hparams.f_ffn_mult = 1.3f; // from the params.json of the 70B model
  923. }
  924. hparams.rope_freq_base = rope_freq_base;
  925. hparams.rope_freq_scale = rope_freq_scale;
  926. }
  927. // ref: https://github.com/facebookresearch/llama/blob/6c7fe276574e78057f917549435a2554000a876d/llama/model.py#L194-L199
  928. const uint32_t n_ff_raw = 2*(4*hparams.n_embd)/3;
  929. const uint32_t n_ff_mult = hparams.f_ffn_mult*n_ff_raw;
  930. const uint32_t n_ff = ((n_ff_mult + hparams.n_mult - 1)/hparams.n_mult)*hparams.n_mult;
  931. //const uint32_t n_ff = 28672;
  932. {
  933. fprintf(stderr, "%s: format = %s\n", __func__, llama_file_version_name(file_version));
  934. fprintf(stderr, "%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  935. fprintf(stderr, "%s: n_ctx = %u\n", __func__, hparams.n_ctx);
  936. fprintf(stderr, "%s: n_embd = %u\n", __func__, hparams.n_embd);
  937. fprintf(stderr, "%s: n_mult = %u\n", __func__, hparams.n_mult);
  938. fprintf(stderr, "%s: n_head = %u\n", __func__, hparams.n_head);
  939. fprintf(stderr, "%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  940. fprintf(stderr, "%s: n_layer = %u\n", __func__, hparams.n_layer);
  941. fprintf(stderr, "%s: n_rot = %u\n", __func__, hparams.n_rot); // a.k.a. n_embd_head, n_head_dim
  942. fprintf(stderr, "%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  943. fprintf(stderr, "%s: rnorm_eps = %.1e\n", __func__, hparams.f_rms_norm_eps);
  944. fprintf(stderr, "%s: n_ff = %u\n", __func__, n_ff);
  945. fprintf(stderr, "%s: freq_base = %.1f\n", __func__, hparams.rope_freq_base);
  946. fprintf(stderr, "%s: freq_scale = %g\n", __func__, hparams.rope_freq_scale);
  947. fprintf(stderr, "%s: ftype = %u (%s)\n", __func__, hparams.ftype, llama_ftype_name(hparams.ftype));
  948. fprintf(stderr, "%s: model size = %s\n", __func__, llama_model_type_name(model.type));
  949. }
  950. if (file_version < LLAMA_FILE_VERSION_GGJT_V2) {
  951. if (hparams.ftype != LLAMA_FTYPE_ALL_F32 &&
  952. hparams.ftype != LLAMA_FTYPE_MOSTLY_F16 &&
  953. hparams.ftype != LLAMA_FTYPE_MOSTLY_Q8_0) {
  954. throw std::runtime_error(format("this format is no longer supported (see https://github.com/ggerganov/llama.cpp/pull/1405)"));
  955. }
  956. }
  957. if (file_version < LLAMA_FILE_VERSION_GGJT_V3) {
  958. if (hparams.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  959. hparams.ftype == LLAMA_FTYPE_MOSTLY_Q4_1 ||
  960. hparams.ftype == LLAMA_FTYPE_MOSTLY_Q8_0) {
  961. throw std::runtime_error(format("this format is no longer supported (see https://github.com/ggerganov/llama.cpp/pull/1508)"));
  962. }
  963. }
  964. if (vocab_only) {
  965. return;
  966. }
  967. auto & ctx = model.ctx;
  968. size_t ctx_size;
  969. size_t mmapped_size;
  970. ml->calc_sizes(&ctx_size, &mmapped_size);
  971. fprintf(stderr, "%s: ggml ctx size = %7.2f MB\n", __func__, ctx_size/1024.0/1024.0);
  972. // create the ggml context
  973. {
  974. model.buf.resize(ctx_size);
  975. if (use_mlock) {
  976. model.mlock_buf.init (model.buf.addr);
  977. model.mlock_buf.grow_to(model.buf.size);
  978. }
  979. struct ggml_init_params params = {
  980. /*.mem_size =*/ model.buf.size,
  981. /*.mem_buffer =*/ model.buf.addr,
  982. /*.no_alloc =*/ ml->use_mmap,
  983. };
  984. model.ctx = ggml_init(params);
  985. if (!model.ctx) {
  986. throw std::runtime_error(format("ggml_init() failed"));
  987. }
  988. }
  989. (void) main_gpu;
  990. (void) mul_mat_q;
  991. #if defined(GGML_USE_CUBLAS)
  992. fprintf(stderr, "%s: using CUDA for GPU acceleration\n", __func__);
  993. ggml_cuda_set_main_device(main_gpu);
  994. ggml_cuda_set_mul_mat_q(mul_mat_q);
  995. #define LLAMA_BACKEND_OFFLOAD GGML_BACKEND_GPU
  996. #define LLAMA_BACKEND_OFFLOAD_SPLIT GGML_BACKEND_GPU_SPLIT
  997. #elif defined(GGML_USE_CLBLAST)
  998. fprintf(stderr, "%s: using OpenCL for GPU acceleration\n", __func__);
  999. #define LLAMA_BACKEND_OFFLOAD GGML_BACKEND_GPU
  1000. #define LLAMA_BACKEND_OFFLOAD_SPLIT GGML_BACKEND_GPU
  1001. #else
  1002. #define LLAMA_BACKEND_OFFLOAD GGML_BACKEND_CPU
  1003. #define LLAMA_BACKEND_OFFLOAD_SPLIT GGML_BACKEND_CPU
  1004. #endif
  1005. // prepare memory for the weights
  1006. size_t vram_weights = 0;
  1007. size_t vram_scratch = 0;
  1008. {
  1009. const uint32_t n_embd = hparams.n_embd;
  1010. const uint32_t n_embd_gqa = hparams.n_embd_gqa();
  1011. const uint32_t n_layer = hparams.n_layer;
  1012. const uint32_t n_vocab = hparams.n_vocab;
  1013. ml->ggml_ctx = ctx;
  1014. model.tok_embeddings = ml->get_tensor("tok_embeddings.weight", {n_embd, n_vocab}, GGML_BACKEND_CPU);
  1015. // "output" tensor
  1016. {
  1017. ggml_backend backend_norm;
  1018. ggml_backend backend_output;
  1019. if (n_gpu_layers > int(n_layer)) { // NOLINT
  1020. // norm is not performance relevant on its own but keeping it in VRAM reduces data copying
  1021. // on Windows however this is detrimental unless everything is on the GPU
  1022. #ifndef _WIN32
  1023. backend_norm = low_vram ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  1024. #else
  1025. backend_norm = low_vram || n_gpu_layers <= (int) n_layer + 2 ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD;
  1026. #endif // _WIN32
  1027. backend_output = LLAMA_BACKEND_OFFLOAD_SPLIT;
  1028. } else {
  1029. backend_norm = GGML_BACKEND_CPU;
  1030. backend_output = GGML_BACKEND_CPU;
  1031. }
  1032. model.norm = ml->get_tensor("norm.weight", {n_embd}, backend_norm);
  1033. model.output = ml->get_tensor("output.weight", {n_embd, n_vocab}, backend_output);
  1034. if (backend_norm == GGML_BACKEND_GPU) {
  1035. vram_weights += ggml_nbytes(model.norm);
  1036. }
  1037. if (backend_output == GGML_BACKEND_GPU_SPLIT) {
  1038. vram_weights += ggml_nbytes(model.output);
  1039. }
  1040. }
  1041. const int i_gpu_start = n_layer - n_gpu_layers;
  1042. model.layers.resize(n_layer);
  1043. for (uint32_t i = 0; i < n_layer; ++i) {
  1044. const ggml_backend backend = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD; // NOLINT
  1045. const ggml_backend backend_split = int(i) < i_gpu_start ? GGML_BACKEND_CPU : LLAMA_BACKEND_OFFLOAD_SPLIT; // NOLINT
  1046. auto & layer = model.layers[i];
  1047. std::string layers_i = "layers." + std::to_string(i);
  1048. layer.attention_norm = ml->get_tensor(layers_i + ".attention_norm.weight", {n_embd}, backend);
  1049. layer.wq = ml->get_tensor(layers_i + ".attention.wq.weight", {n_embd, n_embd}, backend_split);
  1050. layer.wk = ml->get_tensor(layers_i + ".attention.wk.weight", {n_embd, n_embd_gqa}, backend_split);
  1051. layer.wv = ml->get_tensor(layers_i + ".attention.wv.weight", {n_embd, n_embd_gqa}, backend_split);
  1052. layer.wo = ml->get_tensor(layers_i + ".attention.wo.weight", {n_embd, n_embd}, backend_split);
  1053. layer.ffn_norm = ml->get_tensor(layers_i + ".ffn_norm.weight", {n_embd}, backend);
  1054. layer.w1 = ml->get_tensor(layers_i + ".feed_forward.w1.weight", {n_embd, n_ff}, backend_split);
  1055. layer.w2 = ml->get_tensor(layers_i + ".feed_forward.w2.weight", { n_ff, n_embd}, backend_split);
  1056. layer.w3 = ml->get_tensor(layers_i + ".feed_forward.w3.weight", {n_embd, n_ff}, backend_split);
  1057. if (backend == GGML_BACKEND_GPU) {
  1058. vram_weights +=
  1059. ggml_nbytes(layer.attention_norm) + ggml_nbytes(layer.wq) + ggml_nbytes(layer.wk) +
  1060. ggml_nbytes(layer.wv) + ggml_nbytes(layer.wo) + ggml_nbytes(layer.ffn_norm) +
  1061. ggml_nbytes(layer.w1) + ggml_nbytes(layer.w2) + ggml_nbytes(layer.w3);
  1062. }
  1063. }
  1064. }
  1065. ml->done_getting_tensors();
  1066. // print memory requirements
  1067. {
  1068. const size_t scale = memory_type == GGML_TYPE_F32 ? 2 : 1;
  1069. // this is the total memory required to run the inference
  1070. size_t mem_required =
  1071. ctx_size +
  1072. mmapped_size - vram_weights; // weights in VRAM not in memory
  1073. #ifndef LLAMA_USE_ALLOCATOR
  1074. mem_required +=
  1075. MEM_REQ_SCRATCH0(hparams.n_ctx).at(model.type) +
  1076. MEM_REQ_SCRATCH1().at(model.type) +
  1077. MEM_REQ_EVAL().at(model.type);
  1078. #endif
  1079. // this is the memory required by one llama_state
  1080. const size_t mem_required_state =
  1081. scale*hparams.kv_size();
  1082. fprintf(stderr, "%s: mem required = %7.2f MB (+ %7.2f MB per state)\n", __func__,
  1083. mem_required / 1024.0 / 1024.0, mem_required_state / 1024.0 / 1024.0);
  1084. (void) vram_scratch;
  1085. (void) n_batch;
  1086. #ifdef GGML_USE_CUBLAS
  1087. if (low_vram) {
  1088. fprintf(stderr, "%s: not allocating a VRAM scratch buffer due to low VRAM option\n", __func__);
  1089. ggml_cuda_set_scratch_size(0); // disable scratch
  1090. } else {
  1091. const size_t vram_scratch_base = VRAM_REQ_SCRATCH_BASE().at(model.type);
  1092. const size_t vram_scratch_per_context = VRAM_REQ_SCRATCH_PER_CONTEXT().at(model.type);
  1093. vram_scratch = n_batch * (vram_scratch_base + n_ctx * vram_scratch_per_context);
  1094. ggml_cuda_set_scratch_size(vram_scratch);
  1095. if (n_gpu_layers > 0) {
  1096. fprintf(stderr, "%s: allocating batch_size x (%zd kB + n_ctx x %zd B) = %zd MB VRAM for the scratch buffer\n",
  1097. __func__, vram_scratch_base / kB, vram_scratch_per_context,
  1098. (vram_scratch + MB - 1) / MB); // round up
  1099. }
  1100. }
  1101. #endif // GGML_USE_CUBLAS
  1102. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST)
  1103. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  1104. fprintf(stderr, "%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  1105. if (n_gpu_layers > (int) hparams.n_layer) {
  1106. fprintf(stderr, "%s: offloading non-repeating layers to GPU\n", __func__);
  1107. }
  1108. size_t vram_kv_cache = 0;
  1109. #ifdef GGML_USE_CUBLAS
  1110. const int max_backend_supported_layers = hparams.n_layer + 3;
  1111. const int max_offloadable_layers = low_vram ? hparams.n_layer + 1 : hparams.n_layer + 3;
  1112. if (n_gpu_layers > (int) hparams.n_layer + 1) {
  1113. if (low_vram) {
  1114. fprintf(stderr, "%s: cannot offload v cache to GPU due to low VRAM option\n", __func__);
  1115. } else {
  1116. fprintf(stderr, "%s: offloading v cache to GPU\n", __func__);
  1117. vram_kv_cache += hparams.kv_size() / 2;
  1118. }
  1119. }
  1120. if (n_gpu_layers > (int) hparams.n_layer + 2) {
  1121. if (low_vram) {
  1122. fprintf(stderr, "%s: cannot offload k cache to GPU due to low VRAM option\n", __func__);
  1123. } else {
  1124. fprintf(stderr, "%s: offloading k cache to GPU\n", __func__);
  1125. vram_kv_cache += hparams.kv_size() / 2;
  1126. }
  1127. }
  1128. #elif defined(GGML_USE_CLBLAST)
  1129. const int max_backend_supported_layers = hparams.n_layer + 1;
  1130. const int max_offloadable_layers = hparams.n_layer + 1;
  1131. #endif // GGML_USE_CUBLAS
  1132. fprintf(stderr, "%s: offloaded %d/%d layers to GPU\n",
  1133. __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  1134. fprintf(stderr, "%s: total VRAM used: %zu MB\n",
  1135. __func__, (vram_weights + vram_scratch + vram_kv_cache + MB - 1) / MB); // round up
  1136. #else
  1137. (void) n_gpu_layers;
  1138. #endif // defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST)
  1139. }
  1140. // populate `tensors_by_name`
  1141. for (llama_load_tensor & lt : ml->tensors_map.tensors) {
  1142. model.tensors_by_name.emplace_back(lt.name, lt.ggml_tensor);
  1143. }
  1144. (void) tensor_split;
  1145. #if defined(GGML_USE_CUBLAS)
  1146. {
  1147. ggml_cuda_set_tensor_split(tensor_split);
  1148. }
  1149. #endif
  1150. ml->load_all_data(progress_callback, progress_callback_user_data, use_mlock ? &model.mlock_mmap : NULL);
  1151. if (progress_callback) {
  1152. progress_callback(1.0f, progress_callback_user_data);
  1153. }
  1154. model.mapping = std::move(ml->mapping);
  1155. // loading time will be recalculate after the first eval, so
  1156. // we take page faults deferred by mmap() into consideration
  1157. model.t_load_us = ggml_time_us() - model.t_start_us;
  1158. }
  1159. static bool llama_model_load(
  1160. const std::string & fname,
  1161. llama_model & model,
  1162. llama_vocab & vocab,
  1163. int n_ctx,
  1164. int n_batch,
  1165. int n_gqa,
  1166. float rms_norm_eps,
  1167. int n_gpu_layers,
  1168. int main_gpu,
  1169. const float * tensor_split,
  1170. const bool mul_mat_q,
  1171. float rope_freq_base,
  1172. float rope_freq_scale,
  1173. bool low_vram,
  1174. ggml_type memory_type,
  1175. bool use_mmap,
  1176. bool use_mlock,
  1177. bool vocab_only,
  1178. llama_progress_callback progress_callback,
  1179. void *progress_callback_user_data) {
  1180. try {
  1181. llama_model_load_internal(fname, model, vocab, n_ctx, n_batch, n_gqa, rms_norm_eps, n_gpu_layers,
  1182. main_gpu, tensor_split, mul_mat_q, rope_freq_base, rope_freq_scale, low_vram, memory_type,
  1183. use_mmap, use_mlock, vocab_only, progress_callback, progress_callback_user_data);
  1184. return true;
  1185. } catch (const std::exception & err) {
  1186. fprintf(stderr, "error loading model: %s\n", err.what());
  1187. return false;
  1188. }
  1189. }
  1190. static struct ggml_cgraph * llama_build_graph(
  1191. llama_context & lctx,
  1192. const llama_token * tokens,
  1193. const float * embd,
  1194. int n_tokens,
  1195. int n_past) {
  1196. LLAMA_ASSERT((!tokens && embd) || (tokens && !embd));
  1197. const int N = n_tokens;
  1198. const auto & model = lctx.model;
  1199. const auto & hparams = model.hparams;
  1200. const auto & kv_self = lctx.kv_self;
  1201. LLAMA_ASSERT(!!kv_self.ctx);
  1202. const int64_t n_embd = hparams.n_embd;
  1203. const int64_t n_layer = hparams.n_layer;
  1204. const int64_t n_ctx = hparams.n_ctx;
  1205. const int64_t n_head = hparams.n_head;
  1206. const int64_t n_head_kv = hparams.n_head_kv;
  1207. const int64_t n_embd_head = hparams.n_embd_head();
  1208. const int64_t n_embd_gqa = hparams.n_embd_gqa();
  1209. LLAMA_ASSERT(n_embd_head == hparams.n_rot);
  1210. const float freq_base = hparams.rope_freq_base;
  1211. const float freq_scale = hparams.rope_freq_scale;
  1212. const float rms_norm_eps = hparams.f_rms_norm_eps;
  1213. const int n_gpu_layers = model.n_gpu_layers;
  1214. auto & mem_per_token = lctx.mem_per_token;
  1215. auto & buf_compute = lctx.buf_compute;
  1216. struct ggml_init_params params = {
  1217. /*.mem_size =*/ buf_compute.size,
  1218. /*.mem_buffer =*/ buf_compute.addr,
  1219. /*.no_alloc =*/ false,
  1220. };
  1221. #ifdef LLAMA_USE_ALLOCATOR
  1222. params.no_alloc = true;
  1223. #endif
  1224. struct ggml_context * ctx0 = ggml_init(params);
  1225. ggml_cgraph * gf = ggml_new_graph(ctx0);
  1226. struct ggml_tensor * cur;
  1227. struct ggml_tensor * inpL;
  1228. if (tokens) {
  1229. struct ggml_tensor * inp_tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  1230. #ifdef LLAMA_USE_ALLOCATOR
  1231. ggml_allocr_alloc(lctx.alloc, inp_tokens);
  1232. if (!ggml_allocr_is_measure(lctx.alloc)) {
  1233. memcpy(inp_tokens->data, tokens, N*ggml_element_size(inp_tokens));
  1234. }
  1235. #else
  1236. memcpy(inp_tokens->data, tokens, N*ggml_element_size(inp_tokens));
  1237. #endif
  1238. ggml_set_name(inp_tokens, "inp_tokens");
  1239. inpL = ggml_get_rows(ctx0, model.tok_embeddings, inp_tokens);
  1240. } else {
  1241. #ifdef GGML_USE_MPI
  1242. GGML_ASSERT(false && "not implemented");
  1243. #endif
  1244. inpL = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N);
  1245. #ifdef LLAMA_USE_ALLOCATOR
  1246. ggml_allocr_alloc(lctx.alloc, inpL);
  1247. if (!ggml_allocr_is_measure(lctx.alloc)) {
  1248. memcpy(inpL->data, embd, N * n_embd * ggml_element_size(inpL));
  1249. }
  1250. #else
  1251. memcpy(inpL->data, embd, N * n_embd * ggml_element_size(inpL));
  1252. #endif
  1253. }
  1254. const int i_gpu_start = n_layer - n_gpu_layers;
  1255. (void) i_gpu_start;
  1256. // offload functions set the tensor output backend to GPU
  1257. // tensors are GPU-accelerated if any input or the output has been offloaded
  1258. //
  1259. // with the low VRAM option VRAM scratch is disabled in llama_load_model_internal
  1260. // in that case ggml_cuda_assign_buffers has no effect
  1261. offload_func_t offload_func_nr = llama_nop; // nr = non-repeating
  1262. offload_func_t offload_func_kq = llama_nop;
  1263. offload_func_t offload_func_v = llama_nop;
  1264. #ifdef GGML_USE_CUBLAS
  1265. if (n_gpu_layers > n_layer) {
  1266. offload_func_nr = ggml_cuda_assign_buffers;
  1267. }
  1268. if (n_gpu_layers > n_layer + 1) {
  1269. offload_func_v = ggml_cuda_assign_buffers;
  1270. }
  1271. if (n_gpu_layers > n_layer + 2) {
  1272. offload_func_kq = ggml_cuda_assign_buffers;
  1273. }
  1274. #endif // GGML_USE_CUBLAS
  1275. struct ggml_tensor * KQ_scale = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1);
  1276. #ifdef LLAMA_USE_ALLOCATOR
  1277. ggml_allocr_alloc(lctx.alloc, KQ_scale);
  1278. if (!ggml_allocr_is_measure(lctx.alloc)) {
  1279. ggml_set_f32(KQ_scale, 1.0f/sqrtf(float(n_embd)/n_head));
  1280. }
  1281. #else
  1282. ggml_set_f32(KQ_scale, 1.0f/sqrtf(float(n_embd)/n_head));
  1283. #endif
  1284. ggml_set_name(KQ_scale, "1/sqrt(n_embd_head)");
  1285. for (int il = 0; il < n_layer; ++il) {
  1286. ggml_format_name(inpL, "layer_inp_%d", il);
  1287. offload_func_t offload_func = llama_nop;
  1288. #ifdef GGML_USE_CUBLAS
  1289. if (il >= i_gpu_start) {
  1290. offload_func = ggml_cuda_assign_buffers;
  1291. }
  1292. #endif // GGML_USE_CUBLAS
  1293. struct ggml_tensor * inpSA = inpL;
  1294. lctx.use_buf(ctx0, 0);
  1295. // norm
  1296. {
  1297. cur = ggml_rms_norm(ctx0, inpL, rms_norm_eps);
  1298. offload_func(cur);
  1299. ggml_set_name(cur, "rms_norm_0");
  1300. // cur = cur*attention_norm(broadcasted)
  1301. cur = ggml_mul(ctx0, cur, model.layers[il].attention_norm);
  1302. offload_func(cur);
  1303. ggml_set_name(cur, "attention_norm_0");
  1304. }
  1305. // self-attention
  1306. {
  1307. // compute Q and K and RoPE them
  1308. struct ggml_tensor * tmpk = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  1309. offload_func_kq(tmpk);
  1310. ggml_set_name(tmpk, "tmpk");
  1311. struct ggml_tensor * tmpq = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  1312. offload_func_kq(tmpq);
  1313. ggml_set_name(tmpq, "tmpq");
  1314. 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);
  1315. offload_func_kq(Kcur);
  1316. ggml_set_name(Kcur, "Kcur");
  1317. 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);
  1318. offload_func_kq(Qcur);
  1319. ggml_set_name(Qcur, "Qcur");
  1320. // store key and value to memory
  1321. {
  1322. // compute the transposed [N, n_embd] V matrix
  1323. struct ggml_tensor * tmpv = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  1324. offload_func_v(tmpv);
  1325. ggml_set_name(tmpv, "tmpv");
  1326. struct ggml_tensor * Vcur = ggml_transpose(ctx0, ggml_reshape_2d(ctx0, tmpv, n_embd_gqa, N));
  1327. offload_func_v(Vcur);
  1328. ggml_set_name(Vcur, "Vcur");
  1329. 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));
  1330. offload_func_kq(k);
  1331. ggml_set_name(k, "k");
  1332. struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd_gqa,
  1333. ( n_ctx)*ggml_element_size(kv_self.v),
  1334. (il*n_ctx)*ggml_element_size(kv_self.v)*n_embd_gqa + n_past*ggml_element_size(kv_self.v));
  1335. offload_func_v(v);
  1336. ggml_set_name(v, "v");
  1337. // important: storing RoPE-ed version of K in the KV cache!
  1338. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k));
  1339. ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v));
  1340. }
  1341. struct ggml_tensor * Q =
  1342. ggml_permute(ctx0,
  1343. Qcur,
  1344. 0, 2, 1, 3);
  1345. offload_func_kq(Q);
  1346. ggml_set_name(Q, "Q");
  1347. struct ggml_tensor * K =
  1348. ggml_permute(ctx0,
  1349. ggml_reshape_3d(ctx0,
  1350. ggml_view_1d(ctx0, kv_self.k, (n_past + N)*n_embd_gqa, il*n_ctx*ggml_element_size(kv_self.k)*n_embd_gqa),
  1351. n_embd_head, n_head_kv, n_past + N),
  1352. 0, 2, 1, 3);
  1353. offload_func_kq(K);
  1354. ggml_set_name(K, "K");
  1355. // K * Q
  1356. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  1357. offload_func_kq(KQ);
  1358. ggml_set_name(KQ, "KQ");
  1359. // KQ_scaled = KQ / sqrt(n_embd_head)
  1360. // KQ_scaled shape [n_past + N, N, n_head, 1]
  1361. struct ggml_tensor * KQ_scaled = ggml_scale_inplace(ctx0, KQ, KQ_scale);
  1362. offload_func_kq(KQ_scaled);
  1363. ggml_set_name(KQ_scaled, "KQ_scaled");
  1364. // KQ_masked = mask_past(KQ_scaled)
  1365. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf_inplace(ctx0, KQ_scaled, n_past);
  1366. offload_func_kq(KQ_masked);
  1367. ggml_set_name(KQ_masked, "KQ_masked");
  1368. // KQ = soft_max(KQ_masked)
  1369. struct ggml_tensor * KQ_soft_max = ggml_soft_max_inplace(ctx0, KQ_masked);
  1370. offload_func_v(KQ_soft_max);
  1371. ggml_set_name(KQ_soft_max, "KQ_soft_max");
  1372. // split cached V into n_head heads
  1373. struct ggml_tensor * V =
  1374. ggml_view_3d(ctx0, kv_self.v,
  1375. n_past + N, n_embd_head, n_head_kv,
  1376. n_ctx*ggml_element_size(kv_self.v),
  1377. n_ctx*ggml_element_size(kv_self.v)*n_embd_head,
  1378. n_ctx*ggml_element_size(kv_self.v)*n_embd_gqa*il);
  1379. offload_func_v(V);
  1380. ggml_set_name(V, "V");
  1381. #if 1
  1382. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
  1383. offload_func_v(KQV);
  1384. ggml_set_name(KQV, "KQV");
  1385. #else
  1386. // make V contiguous in memory to speed up the matmul, however we waste time on the copy
  1387. // on M1 this is faster for the perplexity computation, but ~5% slower for the single-token generation
  1388. // is there a better way?
  1389. 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));
  1390. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V_cont, KQ_soft_max);
  1391. #endif
  1392. // KQV_merged = KQV.permute(0, 2, 1, 3)
  1393. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  1394. offload_func_v(KQV_merged);
  1395. ggml_set_name(KQV_merged, "KQV_merged");
  1396. // cur = KQV_merged.contiguous().view(n_embd, N)
  1397. cur = ggml_cpy(ctx0,
  1398. KQV_merged,
  1399. ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  1400. offload_func_v(cur);
  1401. ggml_set_name(cur, "KQV_merged_contiguous");
  1402. // projection (no bias)
  1403. cur = ggml_mul_mat(ctx0,
  1404. model.layers[il].wo,
  1405. cur);
  1406. offload_func(cur);
  1407. ggml_set_name(cur, "result_wo");
  1408. }
  1409. lctx.use_buf(ctx0, 1);
  1410. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  1411. offload_func(inpFF);
  1412. ggml_set_name(inpFF, "inpFF");
  1413. // feed-forward network
  1414. {
  1415. // norm
  1416. {
  1417. cur = ggml_rms_norm(ctx0, inpFF, rms_norm_eps);
  1418. offload_func(cur);
  1419. ggml_set_name(cur, "rms_norm_1");
  1420. // cur = cur*ffn_norm(broadcasted)
  1421. cur = ggml_mul(ctx0, cur, model.layers[il].ffn_norm);
  1422. offload_func(cur);
  1423. ggml_set_name(cur, "ffn_norm");
  1424. }
  1425. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  1426. model.layers[il].w3,
  1427. cur);
  1428. offload_func(tmp);
  1429. ggml_set_name(tmp, "result_w3");
  1430. cur = ggml_mul_mat(ctx0,
  1431. model.layers[il].w1,
  1432. cur);
  1433. offload_func(cur);
  1434. ggml_set_name(cur, "result_w1");
  1435. // SILU activation
  1436. cur = ggml_silu(ctx0, cur);
  1437. offload_func(cur);
  1438. ggml_set_name(cur, "silu");
  1439. cur = ggml_mul(ctx0, cur, tmp);
  1440. offload_func(cur);
  1441. ggml_set_name(cur, "silu_x_result_w3");
  1442. cur = ggml_mul_mat(ctx0,
  1443. model.layers[il].w2,
  1444. cur);
  1445. offload_func(cur);
  1446. ggml_set_name(cur, "result_w2");
  1447. }
  1448. cur = ggml_add(ctx0, cur, inpFF);
  1449. offload_func(cur);
  1450. ggml_set_name(cur, "inpFF_+_result_w2");
  1451. // input for next layer
  1452. inpL = cur;
  1453. }
  1454. lctx.use_buf(ctx0, 0);
  1455. // norm
  1456. {
  1457. cur = ggml_rms_norm(ctx0, inpL, rms_norm_eps);
  1458. offload_func_nr(cur);
  1459. ggml_set_name(cur, "rms_norm_2");
  1460. // cur = cur*norm(broadcasted)
  1461. cur = ggml_mul(ctx0, cur, model.norm);
  1462. // offload_func_nr(cur); // TODO CPU + GPU mirrored backend
  1463. ggml_set_name(cur, "result_norm");
  1464. }
  1465. // lm_head
  1466. cur = ggml_mul_mat(ctx0, model.output, cur);
  1467. ggml_set_name(cur, "result_output");
  1468. lctx.use_buf(ctx0, -1);
  1469. // logits -> probs
  1470. //cur = ggml_soft_max_inplace(ctx0, cur);
  1471. ggml_build_forward_expand(gf, cur);
  1472. if (mem_per_token == 0) {
  1473. mem_per_token = ggml_used_mem(ctx0)/N;
  1474. }
  1475. #if 0
  1476. printf("\n%s: used_mem: eval ctx %.3f MB, scratch %.3f MB %.3f MB, work buf %.3f MB, n_past = %d, N = %d\n", __func__,
  1477. ggml_used_mem(ctx0)/1024.0/1024.0,
  1478. lctx.get_buf_max_mem(0)/1024.0/1024.0,
  1479. lctx.get_buf_max_mem(1)/1024.0/1024.0,
  1480. lctx.work_buffer.size()/1024.0/1024.0,
  1481. n_past, N);
  1482. #endif
  1483. ggml_free(ctx0);
  1484. return gf;
  1485. }
  1486. // evaluate the transformer
  1487. //
  1488. // - lctx: llama context
  1489. // - tokens: new batch of tokens to process
  1490. // - embd embeddings input
  1491. // - n_tokens number of tokens
  1492. // - n_past: the context size so far
  1493. // - n_threads: number of threads to use
  1494. //
  1495. static bool llama_eval_internal(
  1496. llama_context & lctx,
  1497. const llama_token * tokens,
  1498. const float * embd,
  1499. int n_tokens,
  1500. int n_past,
  1501. int n_threads,
  1502. const char * cgraph_fname) {
  1503. LLAMA_ASSERT((!tokens && embd) || (tokens && !embd));
  1504. const int64_t t_start_us = ggml_time_us();
  1505. #ifdef GGML_USE_MPI
  1506. ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  1507. #endif
  1508. const int N = n_tokens;
  1509. const auto & model = lctx.model;
  1510. const auto & hparams = model.hparams;
  1511. const auto & kv_self = lctx.kv_self;
  1512. LLAMA_ASSERT(!!kv_self.ctx);
  1513. const int64_t n_embd = hparams.n_embd;
  1514. const int64_t n_vocab = hparams.n_vocab;
  1515. #ifdef LLAMA_USE_ALLOCATOR
  1516. ggml_allocr_reset(lctx.alloc);
  1517. #endif
  1518. ggml_cgraph * gf = llama_build_graph(lctx, tokens, embd, n_tokens, n_past);
  1519. #ifdef LLAMA_USE_ALLOCATOR
  1520. ggml_allocr_alloc_graph(lctx.alloc, gf);
  1521. #endif
  1522. // fprintf(stderr, "graph build time: %.3f ms (%d nodes, %d leafs)\n", (ggml_time_us() - t_start_us)/1000.0, gf->n_nodes, gf->n_leafs);
  1523. // for big prompts, if BLAS is enabled, it is better to use only one thread
  1524. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  1525. n_threads = N >= 32 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas() ? 1 : n_threads;
  1526. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  1527. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 2];
  1528. LLAMA_ASSERT(strcmp(res->name, "result_output") == 0);
  1529. LLAMA_ASSERT(strcmp(embeddings->name, "result_norm") == 0);
  1530. #if GGML_USE_MPI
  1531. const int64_t n_layer = hparams.n_layer;
  1532. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  1533. #endif
  1534. #ifdef GGML_USE_METAL
  1535. if (lctx.ctx_metal && N == 1) {
  1536. // TODO: disabled until #2413 is resolved
  1537. //if (!ggml_metal_if_optimized(lctx.ctx_metal)) {
  1538. // ggml_metal_graph_find_concurrency(lctx.ctx_metal, gf);
  1539. //}
  1540. ggml_metal_set_n_cb (lctx.ctx_metal, n_threads);
  1541. ggml_metal_graph_compute(lctx.ctx_metal, gf);
  1542. ggml_metal_get_tensor (lctx.ctx_metal, res);
  1543. if (!lctx.embedding.empty()) {
  1544. ggml_metal_get_tensor(lctx.ctx_metal, embeddings);
  1545. }
  1546. } else {
  1547. // IMPORTANT:
  1548. // Since we don't have efficient Matrix x Matrix Metal multiplication yet, we fallback to vanilla
  1549. // ggml_graph_compute(). It uses Apple's Accelerate CBLAS API which takes advantage of the ANE or the AMX
  1550. // coprocessor.
  1551. //
  1552. // When we implement Matrix x Matrix Metal multiplication, we can avoid this branch.
  1553. // But for now, we have focused only on Matrix x Vector Metal multiplication.
  1554. //
  1555. // TODO: avoid these syncs via shared memory (ref #1696)
  1556. //
  1557. if (lctx.ctx_metal) {
  1558. // We need to sync the GPU KV cache with the CPU KV cache
  1559. ggml_metal_get_tensor(lctx.ctx_metal, kv_self.k);
  1560. ggml_metal_get_tensor(lctx.ctx_metal, kv_self.v);
  1561. }
  1562. ggml_graph_compute_helper(lctx.work_buffer, gf, n_threads);
  1563. }
  1564. #else
  1565. ggml_graph_compute_helper(lctx.work_buffer, gf, n_threads);
  1566. #endif
  1567. #if GGML_USE_MPI
  1568. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  1569. #endif
  1570. // update kv token count
  1571. lctx.kv_self.n = n_past + N;
  1572. if (cgraph_fname) {
  1573. ggml_graph_export(gf, cgraph_fname);
  1574. }
  1575. #ifdef GGML_PERF
  1576. // print timing information per ggml operation (for debugging purposes)
  1577. // requires GGML_PERF to be defined
  1578. ggml_graph_print(gf);
  1579. #endif
  1580. // plot the computation graph in dot format (for debugging purposes)
  1581. //if (n_past%100 == 0) {
  1582. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  1583. //}
  1584. // extract logits
  1585. {
  1586. auto & logits_out = lctx.logits;
  1587. if (lctx.logits_all) {
  1588. logits_out.resize(n_vocab * N);
  1589. memcpy(logits_out.data(), (float *) ggml_get_data(res), sizeof(float)*n_vocab*N);
  1590. } else {
  1591. // return result for just the last token
  1592. logits_out.resize(n_vocab);
  1593. memcpy(logits_out.data(), (float *) ggml_get_data(res) + (n_vocab*(N-1)), sizeof(float)*n_vocab);
  1594. }
  1595. }
  1596. // extract embeddings
  1597. if (!lctx.embedding.empty()) {
  1598. auto & embedding_out = lctx.embedding;
  1599. embedding_out.resize(n_embd);
  1600. memcpy(embedding_out.data(), (float *) ggml_get_data(embeddings) + (n_embd*(N - 1)), sizeof(float)*n_embd);
  1601. }
  1602. // measure the performance only for the single-token evals
  1603. if (N == 1) {
  1604. lctx.t_eval_us += ggml_time_us() - t_start_us;
  1605. lctx.n_eval++;
  1606. }
  1607. else if (N > 1) {
  1608. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  1609. lctx.n_p_eval += N;
  1610. }
  1611. return true;
  1612. }
  1613. //
  1614. // tokenizer
  1615. //
  1616. static size_t utf8_len(char src) {
  1617. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  1618. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  1619. return lookup[highbits];
  1620. }
  1621. struct llama_sp_symbol {
  1622. using index = int;
  1623. index prev;
  1624. index next;
  1625. const char * text;
  1626. size_t n;
  1627. };
  1628. static_assert(std::is_trivially_copyable<llama_sp_symbol>::value, "llama_sp_symbol is not trivially copyable");
  1629. struct llama_sp_bigram {
  1630. struct comparator {
  1631. bool operator()(llama_sp_bigram & l, llama_sp_bigram & r) {
  1632. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  1633. }
  1634. };
  1635. using queue_storage = std::vector<llama_sp_bigram>;
  1636. using queue = std::priority_queue<llama_sp_bigram, queue_storage, comparator>;
  1637. llama_sp_symbol::index left;
  1638. llama_sp_symbol::index right;
  1639. float score;
  1640. size_t size;
  1641. };
  1642. // original implementation:
  1643. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  1644. struct llama_tokenizer {
  1645. llama_tokenizer(const llama_vocab & vocab): vocab_(vocab) {}
  1646. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  1647. // split string into utf8 chars
  1648. int index = 0;
  1649. size_t offs = 0;
  1650. while (offs < text.size()) {
  1651. llama_sp_symbol sym;
  1652. size_t char_len = std::min(text.size() - offs, utf8_len(text[offs]));
  1653. sym.text = text.c_str() + offs;
  1654. sym.n = char_len;
  1655. offs += char_len;
  1656. sym.prev = index - 1;
  1657. sym.next = offs == text.size() ? -1 : index + 1;
  1658. index++;
  1659. symbols_.emplace_back(sym);
  1660. }
  1661. // seed the work queue with all possible 2-character tokens.
  1662. for (size_t i = 1; i < symbols_.size(); ++i) {
  1663. try_add_bigram(i - 1, i);
  1664. }
  1665. // keep substituting the highest frequency pairs for as long as we can.
  1666. while (!work_queue_.empty()) {
  1667. auto bigram = work_queue_.top();
  1668. work_queue_.pop();
  1669. auto & left_sym = symbols_[bigram.left];
  1670. auto & right_sym = symbols_[bigram.right];
  1671. // if one of the symbols already got merged, skip it.
  1672. if (left_sym.n == 0 || right_sym.n == 0 ||
  1673. left_sym.n + right_sym.n != bigram.size) {
  1674. continue;
  1675. }
  1676. // merge the right sym into the left one
  1677. left_sym.n += right_sym.n;
  1678. right_sym.n = 0;
  1679. //printf("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  1680. // remove the right sym from the chain
  1681. left_sym.next = right_sym.next;
  1682. if (right_sym.next >= 0) {
  1683. symbols_[right_sym.next].prev = bigram.left;
  1684. }
  1685. // find more substitutions
  1686. try_add_bigram(left_sym.prev, bigram.left);
  1687. try_add_bigram(bigram.left, left_sym.next);
  1688. }
  1689. for (int i = 0; i != -1; i = symbols_[i].next) {
  1690. auto & symbol = symbols_[i];
  1691. auto token = vocab_.token_to_id.find(std::string(symbol.text, symbol.n));
  1692. if (token == vocab_.token_to_id.end()) {
  1693. // output any symbols that did not form tokens as bytes.
  1694. for (int j = 0; j < (int) symbol.n; ++j) {
  1695. // NOTE: old version, before #2420 - not sure what are the implications of this
  1696. //llama_vocab::id token_id = static_cast<uint8_t>(symbol.text[j]) + 3;
  1697. llama_vocab::id token_id = vocab_.token_to_id.at(std::string(1, symbol.text[j]));
  1698. output.push_back(token_id);
  1699. }
  1700. } else {
  1701. output.push_back((*token).second);
  1702. }
  1703. }
  1704. }
  1705. private:
  1706. void try_add_bigram(int left, int right) {
  1707. if (left == -1 || right == -1) {
  1708. return;
  1709. }
  1710. const std::string text = std::string(symbols_[left].text, symbols_[left].n + symbols_[right].n);
  1711. auto token = vocab_.token_to_id.find(text);
  1712. if (token == vocab_.token_to_id.end()) {
  1713. return;
  1714. }
  1715. if (static_cast<size_t>((*token).second) >= vocab_.id_to_token.size()) {
  1716. return;
  1717. }
  1718. const auto &tok_score = vocab_.id_to_token[(*token).second];
  1719. llama_sp_bigram bigram;
  1720. bigram.left = left;
  1721. bigram.right = right;
  1722. bigram.score = tok_score.score;
  1723. bigram.size = text.size();
  1724. work_queue_.push(bigram);
  1725. }
  1726. const llama_vocab & vocab_;
  1727. std::vector<llama_sp_symbol> symbols_;
  1728. llama_sp_bigram::queue work_queue_;
  1729. };
  1730. static std::vector<llama_vocab::id> llama_tokenize(const llama_vocab & vocab, const std::string & text, bool bos) {
  1731. llama_tokenizer tokenizer(vocab);
  1732. std::vector<llama_vocab::id> output;
  1733. if (text.empty()) {
  1734. return output;
  1735. }
  1736. if (bos) {
  1737. output.push_back(llama_token_bos());
  1738. }
  1739. tokenizer.tokenize(text, output);
  1740. return output;
  1741. }
  1742. //
  1743. // grammar - internal
  1744. //
  1745. struct llama_grammar {
  1746. const std::vector<std::vector<llama_grammar_element>> rules;
  1747. std::vector<std::vector<const llama_grammar_element *>> stacks;
  1748. };
  1749. struct llama_grammar_candidate {
  1750. size_t index;
  1751. const uint32_t * code_points;
  1752. };
  1753. // NOTE: assumes valid utf8 (but checks for overrun)
  1754. // adds a terminating 0 for use as pointer
  1755. std::vector<uint32_t> decode_utf8(const char * src) {
  1756. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  1757. const char * pos = src;
  1758. std::vector<uint32_t> code_points;
  1759. while (*pos != 0) {
  1760. uint8_t first_byte = static_cast<uint8_t>(*pos);
  1761. uint8_t highbits = first_byte >> 4;
  1762. int len = lookup[highbits];
  1763. uint8_t mask = (1 << (8 - len)) - 1;
  1764. uint32_t value = first_byte & mask;
  1765. const char * end = pos + len; // may overrun!
  1766. ++pos;
  1767. for ( ; pos < end && *pos != 0; ++pos) {
  1768. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  1769. }
  1770. code_points.push_back(value);
  1771. }
  1772. code_points.push_back(0);
  1773. return code_points;
  1774. }
  1775. // returns true iff pos points to the end of one of the definitions of a rule
  1776. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  1777. switch (pos->type) {
  1778. case LLAMA_GRETYPE_END: return true;
  1779. case LLAMA_GRETYPE_ALT: return true;
  1780. default: return false;
  1781. }
  1782. }
  1783. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  1784. // asserts that pos is pointing to a char range element
  1785. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  1786. const llama_grammar_element * pos,
  1787. const uint32_t chr) {
  1788. bool found = false;
  1789. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  1790. LLAMA_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  1791. do {
  1792. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  1793. // inclusive range, e.g. [a-z]
  1794. found = found || (pos->value <= chr && chr <= pos[1].value);
  1795. pos += 2;
  1796. } else {
  1797. // exact char match, e.g. [a] or "a"
  1798. found = found || pos->value == chr;
  1799. pos += 1;
  1800. }
  1801. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  1802. return std::make_pair(found == is_positive_char, pos);
  1803. }
  1804. // transforms a grammar pushdown stack into N possible stacks, all ending
  1805. // at a character range (terminal element)
  1806. static void llama_grammar_advance_stack(
  1807. const std::vector<std::vector<llama_grammar_element>> & rules,
  1808. const std::vector<const llama_grammar_element *> & stack,
  1809. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  1810. if (stack.empty()) {
  1811. new_stacks.push_back(stack);
  1812. return;
  1813. }
  1814. const llama_grammar_element * pos = stack.back();
  1815. switch (pos->type) {
  1816. case LLAMA_GRETYPE_RULE_REF: {
  1817. const size_t rule_id = static_cast<size_t>(pos->value);
  1818. const llama_grammar_element * subpos = rules[rule_id].data();
  1819. do {
  1820. // init new stack without the top (pos)
  1821. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  1822. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  1823. // if this rule ref is followed by another element, add that to stack
  1824. new_stack.push_back(pos + 1);
  1825. }
  1826. if (!llama_grammar_is_end_of_sequence(subpos)) {
  1827. // if alternate is nonempty, add to stack
  1828. new_stack.push_back(subpos);
  1829. }
  1830. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  1831. while (!llama_grammar_is_end_of_sequence(subpos)) {
  1832. // scan to end of alternate def
  1833. subpos++;
  1834. }
  1835. if (subpos->type == LLAMA_GRETYPE_ALT) {
  1836. // there's another alternate def of this rule to process
  1837. subpos++;
  1838. } else {
  1839. break;
  1840. }
  1841. } while (true);
  1842. break;
  1843. }
  1844. case LLAMA_GRETYPE_CHAR:
  1845. case LLAMA_GRETYPE_CHAR_NOT:
  1846. new_stacks.push_back(stack);
  1847. break;
  1848. default:
  1849. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  1850. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  1851. // those
  1852. LLAMA_ASSERT(false);
  1853. }
  1854. }
  1855. // takes a set of possible pushdown stacks on a grammar, which are required to
  1856. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  1857. // produces the N possible stacks if the given char is accepted at those
  1858. // positions
  1859. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  1860. const std::vector<std::vector<llama_grammar_element>> & rules,
  1861. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  1862. const uint32_t chr) {
  1863. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  1864. for (const auto & stack : stacks) {
  1865. if (stack.empty()) {
  1866. continue;
  1867. }
  1868. auto match = llama_grammar_match_char(stack.back(), chr);
  1869. if (match.first) {
  1870. const llama_grammar_element * pos = match.second;
  1871. // update top of stack to next element, if any
  1872. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  1873. if (!llama_grammar_is_end_of_sequence(pos)) {
  1874. new_stack.push_back(pos);
  1875. }
  1876. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  1877. }
  1878. }
  1879. return new_stacks;
  1880. }
  1881. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  1882. const std::vector<std::vector<llama_grammar_element>> & rules,
  1883. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  1884. const std::vector<llama_grammar_candidate> & candidates);
  1885. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  1886. const std::vector<std::vector<llama_grammar_element>> & rules,
  1887. const std::vector<const llama_grammar_element *> & stack,
  1888. const std::vector<llama_grammar_candidate> & candidates) {
  1889. std::vector<llama_grammar_candidate> rejects;
  1890. if (stack.empty()) {
  1891. // accept nothing; EOS is handled elsewhere
  1892. rejects.insert(rejects.end(), candidates.begin(), candidates.end());
  1893. return rejects;
  1894. }
  1895. const llama_grammar_element * stack_pos = stack.back();
  1896. std::vector<llama_grammar_candidate> next_candidates;
  1897. for (auto tok : candidates) {
  1898. if (llama_grammar_match_char(stack_pos, tok.code_points[0]).first) {
  1899. if (tok.code_points[1] != 0) {
  1900. next_candidates.push_back({ tok.index, tok.code_points + 1 });
  1901. }
  1902. } else {
  1903. rejects.push_back(tok);
  1904. }
  1905. }
  1906. auto stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  1907. // update top of stack to next element, if any
  1908. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  1909. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  1910. stack_after.push_back(stack_pos_after);
  1911. }
  1912. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  1913. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  1914. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  1915. for (auto tok : next_rejects) {
  1916. rejects.push_back({ tok.index, tok.code_points - 1 });
  1917. }
  1918. return rejects;
  1919. }
  1920. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  1921. const std::vector<std::vector<llama_grammar_element>> & rules,
  1922. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  1923. const std::vector<llama_grammar_candidate> & candidates) {
  1924. LLAMA_ASSERT(!stacks.empty()); // REVIEW
  1925. if (candidates.empty()) {
  1926. return std::vector<llama_grammar_candidate>();
  1927. }
  1928. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  1929. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  1930. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  1931. }
  1932. return rejects;
  1933. }
  1934. //
  1935. // grammar - external
  1936. //
  1937. struct llama_grammar * llama_grammar_init(
  1938. const llama_grammar_element ** rules,
  1939. size_t n_rules,
  1940. size_t start_rule_index) {
  1941. const llama_grammar_element * pos;
  1942. // copy rule definitions into vectors
  1943. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  1944. for (size_t i = 0; i < n_rules; i++) {
  1945. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  1946. vec_rules[i].push_back(*pos);
  1947. }
  1948. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  1949. }
  1950. // loop over alternates of start rule to build initial stacks
  1951. std::vector<std::vector<const llama_grammar_element *>> stacks;
  1952. pos = rules[start_rule_index];
  1953. do {
  1954. std::vector<const llama_grammar_element *> stack;
  1955. if (!llama_grammar_is_end_of_sequence(pos)) {
  1956. // if alternate is nonempty, add to stack
  1957. stack.push_back(pos);
  1958. }
  1959. llama_grammar_advance_stack(vec_rules, stack, stacks);
  1960. while (!llama_grammar_is_end_of_sequence(pos)) {
  1961. // scan to end of alternate def
  1962. pos++;
  1963. }
  1964. if (pos->type == LLAMA_GRETYPE_ALT) {
  1965. // there's another alternate def of this rule to process
  1966. pos++;
  1967. } else {
  1968. break;
  1969. }
  1970. } while (true);
  1971. return new llama_grammar{ std::move(vec_rules), std::move(stacks) };
  1972. }
  1973. void llama_grammar_free(struct llama_grammar * grammar) {
  1974. delete grammar;
  1975. }
  1976. //
  1977. // sampling
  1978. //
  1979. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  1980. assert(candidates->size > 0);
  1981. const int64_t t_start_sample_us = ggml_time_us();
  1982. // Sort the logits in descending order
  1983. if (!candidates->sorted) {
  1984. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  1985. return a.logit > b.logit;
  1986. });
  1987. candidates->sorted = true;
  1988. }
  1989. float max_l = candidates->data[0].logit;
  1990. float cum_sum = 0.0f;
  1991. for (size_t i = 0; i < candidates->size; ++i) {
  1992. float p = expf(candidates->data[i].logit - max_l);
  1993. candidates->data[i].p = p;
  1994. cum_sum += p;
  1995. }
  1996. for (size_t i = 0; i < candidates->size; ++i) {
  1997. candidates->data[i].p /= cum_sum;
  1998. }
  1999. if (ctx) {
  2000. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2001. }
  2002. }
  2003. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int k, size_t min_keep) {
  2004. const int64_t t_start_sample_us = ggml_time_us();
  2005. k = std::max(k, (int) min_keep);
  2006. k = std::min(k, (int) candidates->size);
  2007. // Sort scores in descending order
  2008. if (!candidates->sorted) {
  2009. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  2010. return a.logit > b.logit;
  2011. };
  2012. if (k == (int) candidates->size) {
  2013. std::sort(candidates->data, candidates->data + candidates->size, comp);
  2014. } else {
  2015. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  2016. }
  2017. candidates->sorted = true;
  2018. }
  2019. candidates->size = k;
  2020. if (ctx) {
  2021. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2022. }
  2023. }
  2024. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  2025. if (p >= 1.0f) {
  2026. return;
  2027. }
  2028. llama_sample_softmax(ctx, candidates);
  2029. const int64_t t_start_sample_us = ggml_time_us();
  2030. // Compute the cumulative probabilities
  2031. float cum_sum = 0.0f;
  2032. size_t last_idx = candidates->size;
  2033. for (size_t i = 0; i < candidates->size; ++i) {
  2034. cum_sum += candidates->data[i].p;
  2035. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  2036. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  2037. if (cum_sum >= p && i + 1 >= min_keep) {
  2038. last_idx = i + 1;
  2039. break;
  2040. }
  2041. }
  2042. // Resize the output vector to keep only the top-p tokens
  2043. candidates->size = last_idx;
  2044. if (ctx) {
  2045. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2046. }
  2047. }
  2048. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  2049. if (z >= 1.0f || candidates->size <= 2) {
  2050. return;
  2051. }
  2052. llama_sample_softmax(nullptr, candidates);
  2053. const int64_t t_start_sample_us = ggml_time_us();
  2054. // Compute the first and second derivatives
  2055. std::vector<float> first_derivatives(candidates->size - 1);
  2056. std::vector<float> second_derivatives(candidates->size - 2);
  2057. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  2058. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  2059. }
  2060. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  2061. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  2062. }
  2063. // Calculate absolute value of second derivatives
  2064. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  2065. second_derivatives[i] = abs(second_derivatives[i]);
  2066. }
  2067. // Normalize the second derivatives
  2068. {
  2069. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  2070. if (second_derivatives_sum > 1e-6f) {
  2071. for (float & value : second_derivatives) {
  2072. value /= second_derivatives_sum;
  2073. }
  2074. } else {
  2075. for (float & value : second_derivatives) {
  2076. value = 1.0f / second_derivatives.size();
  2077. }
  2078. }
  2079. }
  2080. float cum_sum = 0.0f;
  2081. size_t last_idx = candidates->size;
  2082. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  2083. cum_sum += second_derivatives[i];
  2084. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  2085. if (cum_sum > z && i >= min_keep) {
  2086. last_idx = i;
  2087. break;
  2088. }
  2089. }
  2090. // Resize the output vector to keep only the tokens above the tail location
  2091. candidates->size = last_idx;
  2092. if (ctx) {
  2093. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2094. }
  2095. }
  2096. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  2097. // Reference implementation:
  2098. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  2099. if (p >= 1.0f) {
  2100. return;
  2101. }
  2102. // Compute the softmax of logits and calculate entropy
  2103. llama_sample_softmax(nullptr, candidates);
  2104. const int64_t t_start_sample_us = ggml_time_us();
  2105. float entropy = 0.0f;
  2106. for (size_t i = 0; i < candidates->size; ++i) {
  2107. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  2108. }
  2109. // Compute the absolute difference between negative log probability and entropy for each candidate
  2110. std::vector<float> shifted_scores;
  2111. for (size_t i = 0; i < candidates->size; ++i) {
  2112. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  2113. shifted_scores.push_back(shifted_score);
  2114. }
  2115. // Sort tokens based on the shifted_scores and their corresponding indices
  2116. std::vector<size_t> indices(candidates->size);
  2117. std::iota(indices.begin(), indices.end(), 0);
  2118. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  2119. return shifted_scores[a] < shifted_scores[b];
  2120. });
  2121. // Compute the cumulative probabilities
  2122. float cum_sum = 0.0f;
  2123. size_t last_idx = indices.size();
  2124. for (size_t i = 0; i < indices.size(); ++i) {
  2125. size_t idx = indices[i];
  2126. cum_sum += candidates->data[idx].p;
  2127. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  2128. if (cum_sum > p && i >= min_keep - 1) {
  2129. last_idx = i + 1;
  2130. break;
  2131. }
  2132. }
  2133. // Resize the output vector to keep only the locally typical tokens
  2134. std::vector<llama_token_data> new_candidates;
  2135. for (size_t i = 0; i < last_idx; ++i) {
  2136. size_t idx = indices[i];
  2137. new_candidates.push_back(candidates->data[idx]);
  2138. }
  2139. // Replace the data in candidates with the new_candidates data
  2140. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  2141. candidates->size = new_candidates.size();
  2142. if (ctx) {
  2143. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2144. }
  2145. }
  2146. void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  2147. const int64_t t_start_sample_us = ggml_time_us();
  2148. for (size_t i = 0; i < candidates_p->size; ++i) {
  2149. candidates_p->data[i].logit /= temp;
  2150. }
  2151. if (ctx) {
  2152. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2153. }
  2154. }
  2155. 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) {
  2156. if (last_tokens_size == 0 || penalty == 1.0f) {
  2157. return;
  2158. }
  2159. const int64_t t_start_sample_us = ggml_time_us();
  2160. for (size_t i = 0; i < candidates->size; ++i) {
  2161. const auto * token_iter = std::find(last_tokens, last_tokens + last_tokens_size, candidates->data[i].id);
  2162. if (token_iter == last_tokens + last_tokens_size) {
  2163. continue;
  2164. }
  2165. // 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.
  2166. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  2167. if (candidates->data[i].logit <= 0) {
  2168. candidates->data[i].logit *= penalty;
  2169. } else {
  2170. candidates->data[i].logit /= penalty;
  2171. }
  2172. }
  2173. candidates->sorted = false;
  2174. if (ctx) {
  2175. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2176. }
  2177. }
  2178. 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) {
  2179. if (last_tokens_size == 0 || (alpha_frequency == 0.0f && alpha_presence == 0.0f)) {
  2180. return;
  2181. }
  2182. const int64_t t_start_sample_us = ggml_time_us();
  2183. // Create a frequency map to count occurrences of each token in last_tokens
  2184. std::unordered_map<llama_token, int> token_count;
  2185. for (size_t i = 0; i < last_tokens_size; ++i) {
  2186. token_count[last_tokens_p[i]]++;
  2187. }
  2188. // Apply frequency and presence penalties to the candidates
  2189. for (size_t i = 0; i < candidates->size; ++i) {
  2190. auto token_iter = token_count.find(candidates->data[i].id);
  2191. if (token_iter == token_count.end()) {
  2192. continue;
  2193. }
  2194. int count = token_iter->second;
  2195. candidates->data[i].logit -= float(count) * alpha_frequency + float(count > 0) * alpha_presence;
  2196. }
  2197. candidates->sorted = false;
  2198. if (ctx) {
  2199. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2200. }
  2201. }
  2202. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  2203. assert(ctx);
  2204. const int64_t t_start_sample_us = ggml_time_us();
  2205. bool allow_eos = false;
  2206. for (const auto & stack : grammar->stacks) {
  2207. if (stack.empty()) {
  2208. allow_eos = true;
  2209. break;
  2210. }
  2211. }
  2212. const llama_token eos = llama_token_eos();
  2213. std::vector<std::vector<uint32_t>> candidates_decoded;
  2214. std::vector<llama_grammar_candidate> candidates_grammar;
  2215. for (size_t i = 0; i < candidates->size; ++i) {
  2216. const llama_token id = candidates->data[i].id;
  2217. const char * str = llama_token_to_str(ctx, id);
  2218. if (id == eos) {
  2219. if (!allow_eos) {
  2220. candidates->data[i].logit = -INFINITY;
  2221. }
  2222. } else if (*str == 0) {
  2223. candidates->data[i].logit = -INFINITY;
  2224. } else {
  2225. candidates_decoded.push_back(decode_utf8(str));
  2226. candidates_grammar.push_back({ i, candidates_decoded.back().data() });
  2227. }
  2228. }
  2229. const auto rejects =
  2230. llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  2231. for (auto & reject : rejects) {
  2232. candidates->data[reject.index].logit = -INFINITY;
  2233. }
  2234. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2235. }
  2236. static void llama_log_softmax(float * array, size_t size) {
  2237. float max_l = *std::max_element(array, array + size);
  2238. float sum = 0.f;
  2239. for (size_t i = 0; i < size; ++i) {
  2240. float p = expf(array[i] - max_l);
  2241. sum += p;
  2242. array[i] = p;
  2243. }
  2244. for (size_t i = 0; i < size; ++i) {
  2245. array[i] = logf(array[i] / sum);
  2246. }
  2247. }
  2248. void llama_sample_classifier_free_guidance(
  2249. struct llama_context * ctx,
  2250. llama_token_data_array * candidates,
  2251. struct llama_context * guidance_ctx,
  2252. float scale) {
  2253. int64_t t_start_sample_us = ggml_time_us();
  2254. assert(ctx);
  2255. auto n_vocab = llama_n_vocab(ctx);
  2256. assert(n_vocab == (int)candidates->size);
  2257. assert(!candidates->sorted);
  2258. std::vector<float> logits_base;
  2259. logits_base.reserve(candidates->size);
  2260. for (size_t i = 0; i < candidates->size; ++i) {
  2261. logits_base.push_back(candidates->data[i].logit);
  2262. }
  2263. llama_log_softmax(logits_base.data(), candidates->size);
  2264. float* logits_guidance = llama_get_logits(guidance_ctx);
  2265. llama_log_softmax(logits_guidance, n_vocab);
  2266. for (int i = 0; i < n_vocab; ++i) {
  2267. float logit_guidance = logits_guidance[i];
  2268. float logit_base = logits_base[i];
  2269. candidates->data[i].logit = scale * (logit_base - logit_guidance) + logit_guidance;
  2270. }
  2271. if (ctx) {
  2272. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2273. }
  2274. }
  2275. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int m, float * mu) {
  2276. assert(ctx);
  2277. auto N = float(llama_n_vocab(ctx));
  2278. int64_t t_start_sample_us;
  2279. t_start_sample_us = ggml_time_us();
  2280. llama_sample_softmax(nullptr, candidates);
  2281. // Estimate s_hat using the most probable m tokens
  2282. float s_hat = 0.0;
  2283. float sum_ti_bi = 0.0;
  2284. float sum_ti_sq = 0.0;
  2285. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  2286. float t_i = logf(float(i + 2) / float(i + 1));
  2287. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  2288. sum_ti_bi += t_i * b_i;
  2289. sum_ti_sq += t_i * t_i;
  2290. }
  2291. s_hat = sum_ti_bi / sum_ti_sq;
  2292. // Compute k from the estimated s_hat and target surprise value
  2293. float epsilon_hat = s_hat - 1;
  2294. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  2295. // Sample the next word X using top-k sampling
  2296. llama_sample_top_k(nullptr, candidates, int(k), 1);
  2297. if (ctx) {
  2298. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2299. }
  2300. llama_token X = llama_sample_token(ctx, candidates);
  2301. t_start_sample_us = ggml_time_us();
  2302. // Compute error as the difference between observed surprise and target surprise value
  2303. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  2304. return candidate.id == X;
  2305. }));
  2306. float observed_surprise = -log2f(candidates->data[X_idx].p);
  2307. float e = observed_surprise - tau;
  2308. // Update mu using the learning rate and error
  2309. *mu = *mu - eta * e;
  2310. if (ctx) {
  2311. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2312. }
  2313. return X;
  2314. }
  2315. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  2316. int64_t t_start_sample_us;
  2317. t_start_sample_us = ggml_time_us();
  2318. llama_sample_softmax(ctx, candidates);
  2319. // Truncate the words with surprise values greater than mu
  2320. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  2321. return -log2f(candidate.p) > *mu;
  2322. }));
  2323. if (candidates->size == 0) {
  2324. candidates->size = 1;
  2325. }
  2326. if (ctx) {
  2327. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2328. }
  2329. // Normalize the probabilities of the remaining words
  2330. llama_sample_softmax(ctx, candidates);
  2331. // Sample the next word X from the remaining words
  2332. llama_token X = llama_sample_token(ctx, candidates);
  2333. t_start_sample_us = ggml_time_us();
  2334. // Compute error as the difference between observed surprise and target surprise value
  2335. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  2336. return candidate.id == X;
  2337. }));
  2338. float observed_surprise = -log2f(candidates->data[X_idx].p);
  2339. float e = observed_surprise - tau;
  2340. // Update mu using the learning rate and error
  2341. *mu = *mu - eta * e;
  2342. if (ctx) {
  2343. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2344. }
  2345. return X;
  2346. }
  2347. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  2348. const int64_t t_start_sample_us = ggml_time_us();
  2349. // Find max element
  2350. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  2351. return a.logit < b.logit;
  2352. });
  2353. llama_token result = max_iter->id;
  2354. if (ctx) {
  2355. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2356. ctx->n_sample++;
  2357. }
  2358. return result;
  2359. }
  2360. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  2361. assert(ctx);
  2362. const int64_t t_start_sample_us = ggml_time_us();
  2363. llama_sample_softmax(nullptr, candidates);
  2364. std::vector<float> probs;
  2365. probs.reserve(candidates->size);
  2366. for (size_t i = 0; i < candidates->size; ++i) {
  2367. probs.push_back(candidates->data[i].p);
  2368. }
  2369. std::discrete_distribution<> dist(probs.begin(), probs.end());
  2370. auto & rng = ctx->rng;
  2371. int idx = dist(rng);
  2372. llama_token result = candidates->data[idx].id;
  2373. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2374. ctx->n_sample++;
  2375. return result;
  2376. }
  2377. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  2378. const int64_t t_start_sample_us = ggml_time_us();
  2379. if (token == llama_token_eos()) {
  2380. for (const auto & stack : grammar->stacks) {
  2381. if (stack.empty()) {
  2382. return;
  2383. }
  2384. }
  2385. LLAMA_ASSERT(false);
  2386. }
  2387. const char * str = llama_token_to_str(ctx, token);
  2388. // Note terminating 0 in decoded string
  2389. auto code_points = decode_utf8(str);
  2390. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  2391. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  2392. }
  2393. LLAMA_ASSERT(!grammar->stacks.empty());
  2394. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  2395. }
  2396. //
  2397. // quantization
  2398. //
  2399. static void llama_convert_tensor_internal(const llama_load_tensor & tensor, llama_buffer & output, const int nelements, const int nthread) {
  2400. if (output.size < nelements * sizeof(float)) {
  2401. output.resize(nelements * sizeof(float));
  2402. }
  2403. float * f32_output = (float *) output.addr;
  2404. ggml_type_traits_t qtype;
  2405. if (ggml_is_quantized(tensor.type)) {
  2406. qtype = ggml_internal_get_type_traits(tensor.type);
  2407. if (qtype.to_float == NULL) {
  2408. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor.type)));
  2409. }
  2410. } else if (tensor.type != GGML_TYPE_F16) {
  2411. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor.type)));
  2412. }
  2413. if (nthread < 2) {
  2414. if (tensor.type == GGML_TYPE_F16) {
  2415. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor.data, f32_output, nelements);
  2416. } else if (ggml_is_quantized(tensor.type)) {
  2417. qtype.to_float(tensor.data, f32_output, nelements);
  2418. } else {
  2419. LLAMA_ASSERT(false); // unreachable
  2420. }
  2421. return;
  2422. }
  2423. auto block_size = tensor.type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor.type);
  2424. auto block_size_bytes = ggml_type_size(tensor.type);
  2425. LLAMA_ASSERT(nelements % block_size == 0);
  2426. auto nblocks = nelements / block_size;
  2427. auto blocks_per_thread = nblocks / nthread;
  2428. auto spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  2429. std::vector<std::thread> workers;
  2430. for (auto tnum = 0, in_buff_offs = 0, out_buff_offs = 0; tnum < nthread; tnum++) {
  2431. auto thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  2432. auto thr_elems = thr_blocks * block_size; // number of elements for this thread
  2433. auto thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  2434. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  2435. if (typ == GGML_TYPE_F16) {
  2436. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  2437. } else {
  2438. qtype.to_float(inbuf, outbuf, nels);
  2439. }
  2440. };
  2441. workers.push_back(std::thread(compute, tensor.type, tensor.data + in_buff_offs, f32_output + out_buff_offs, thr_elems));
  2442. in_buff_offs += thr_block_bytes;
  2443. out_buff_offs += thr_elems;
  2444. }
  2445. for (auto & worker : workers) {
  2446. worker.join();
  2447. }
  2448. }
  2449. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  2450. ggml_type quantized_type;
  2451. llama_ftype ftype = params->ftype;
  2452. int nthread = params->nthread;
  2453. switch (params->ftype) {
  2454. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  2455. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  2456. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  2457. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  2458. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  2459. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  2460. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  2461. #ifdef GGML_USE_K_QUANTS
  2462. // K-quants
  2463. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  2464. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  2465. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  2466. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  2467. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  2468. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  2469. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  2470. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  2471. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  2472. #endif
  2473. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  2474. }
  2475. if (nthread <= 0) {
  2476. nthread = std::thread::hardware_concurrency();
  2477. }
  2478. std::unique_ptr<llama_model_loader> model_loader(new llama_model_loader(fname_inp, /*use_mmap*/ false));
  2479. llama_file_saver file_saver(fname_out.c_str(), model_loader->file_loader.get(), params->ftype);
  2480. #ifdef GGML_USE_K_QUANTS
  2481. int n_attention_wv = 0;
  2482. int n_feed_forward_w2 = 0;
  2483. for (auto& tensor : model_loader->tensors_map.tensors) {
  2484. if (tensor.name.find("attention.wv.weight") != std::string::npos) {
  2485. ++n_attention_wv;
  2486. }
  2487. else if (tensor.name.find("feed_forward.w2.weight") != std::string::npos) {
  2488. ++n_feed_forward_w2;
  2489. }
  2490. }
  2491. int i_attention_wv = 0;
  2492. int i_feed_forward_w2 = 0;
  2493. #endif
  2494. size_t total_size_org = 0;
  2495. size_t total_size_new = 0;
  2496. std::vector<int64_t> hist_all(1 << 4, 0);
  2497. std::vector<std::thread> workers;
  2498. std::mutex mutex;
  2499. auto use_more_bits = [] (int i_layer, int num_layers) -> bool {
  2500. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  2501. };
  2502. size_t idx = 0;
  2503. for (llama_load_tensor & tensor : model_loader->tensors_map.tensors) {
  2504. llama_buffer read_data;
  2505. read_data.resize(tensor.size);
  2506. tensor.data = read_data.addr;
  2507. model_loader->load_data_for(tensor);
  2508. printf("[%4zu/%4zu] %36s - %16s, type = %6s, ",
  2509. ++idx, model_loader->tensors_map.tensors.size(),
  2510. tensor.name.c_str(), llama_format_tensor_shape(tensor.ne).c_str(),
  2511. ggml_type_name(tensor.type));
  2512. // This used to be a regex, but <regex> has an extreme cost to compile times.
  2513. bool quantize = tensor.name.rfind("weight") == tensor.name.size() - 6; // ends with 'weight'?
  2514. // quantize only 2D tensors
  2515. quantize &= (tensor.ne.size() == 2);
  2516. quantize &= params->quantize_output_tensor || tensor.name != "output.weight";
  2517. quantize &= quantized_type != tensor.type;
  2518. enum ggml_type new_type;
  2519. void * new_data;
  2520. size_t new_size;
  2521. llama_buffer work;
  2522. if (!quantize) {
  2523. new_type = tensor.type;
  2524. new_data = tensor.data;
  2525. new_size = tensor.size;
  2526. printf("size = %8.3f MB\n", tensor.size/1024.0/1024.0);
  2527. } else {
  2528. new_type = quantized_type;
  2529. #ifdef GGML_USE_K_QUANTS
  2530. if (tensor.name == "output.weight") {
  2531. int nx = tensor.ne.at(0);
  2532. int ny = tensor.ne.at(1);
  2533. if (nx % QK_K == 0 && ny % QK_K == 0) {
  2534. new_type = GGML_TYPE_Q6_K;
  2535. }
  2536. } else if (tensor.name.find("attention.wv.weight") != std::string::npos) {
  2537. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q4_K;
  2538. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  2539. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  2540. use_more_bits(i_attention_wv, n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  2541. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  2542. (i_attention_wv < n_attention_wv/8 || i_attention_wv >= 7*n_attention_wv/8)) new_type = GGML_TYPE_Q6_K;
  2543. ++i_attention_wv;
  2544. } else if (tensor.name.find("feed_forward.w2.weight") != std::string::npos) {
  2545. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q4_K;
  2546. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  2547. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  2548. use_more_bits(i_feed_forward_w2, n_feed_forward_w2)) new_type = GGML_TYPE_Q6_K;
  2549. //else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && i_feed_forward_w2 < n_feed_forward_w2/8) new_type = GGML_TYPE_Q6_K;
  2550. ++i_feed_forward_w2;
  2551. } else if (tensor.name.find("attention.wo.weight") != std::string::npos) {
  2552. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q4_K;
  2553. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  2554. }
  2555. bool convert_incompatible_tensor = false;
  2556. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  2557. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K) {
  2558. int nx = tensor.ne.at(0);
  2559. int ny = tensor.ne.at(1);
  2560. if (nx % QK_K != 0 || ny % QK_K != 0) {
  2561. fprintf(stderr, "\n\nTensor sizes %d x %d are not divisible by %d, required for k-quants.\n",nx,ny,QK_K);
  2562. convert_incompatible_tensor = true;
  2563. }
  2564. }
  2565. if (convert_incompatible_tensor) {
  2566. if (tensor.name == "output.weight") {
  2567. new_type = GGML_TYPE_F16; //fall back to F16 instead of just failing.
  2568. fprintf(stderr, "F16 will be used for this tensor instead.\n");
  2569. } else if (tensor.name == "tok_embeddings.weight") {
  2570. new_type = GGML_TYPE_Q4_0; //fall back to Q4_0 instead of just failing.
  2571. fprintf(stderr, "Q4_0 will be used for this tensor instead.\n");
  2572. } else {
  2573. throw std::runtime_error("Unsupported tensor size encountered\n");
  2574. }
  2575. }
  2576. #endif
  2577. float * f32_data;
  2578. size_t nelements = tensor.ne.at(0) * tensor.ne.at(1);
  2579. llama_buffer f32_conv_buf;
  2580. if (tensor.type == GGML_TYPE_F32) {
  2581. f32_data = (float *) tensor.data;
  2582. } else if (ggml_is_quantized(tensor.type) && !params->allow_requantize) {
  2583. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor.type)));
  2584. } else {
  2585. llama_convert_tensor_internal(tensor, f32_conv_buf, nelements, nthread);
  2586. f32_data = (float *) f32_conv_buf.addr;
  2587. }
  2588. printf("quantizing to %s .. ", ggml_type_name(new_type));
  2589. fflush(stdout);
  2590. work.resize(nelements * 4); // upper bound on size
  2591. new_data = work.addr;
  2592. std::vector<int64_t> hist_cur(1 << 4, 0);
  2593. int chunk_size = 32 * 512;
  2594. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  2595. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  2596. if (nthread_use < 2) {
  2597. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nelements, hist_cur.data());
  2598. } else {
  2599. size_t counter = 0;
  2600. new_size = 0;
  2601. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, nelements, chunk_size] () {
  2602. std::vector<int64_t> local_hist;
  2603. size_t local_size = 0;
  2604. while (true) {
  2605. std::unique_lock<std::mutex> lock(mutex);
  2606. size_t first = counter; counter += chunk_size;
  2607. if (first >= nelements) {
  2608. if (!local_hist.empty()) {
  2609. for (int j=0; j<int(local_hist.size()); ++j) {
  2610. hist_cur[j] += local_hist[j];
  2611. }
  2612. new_size += local_size;
  2613. }
  2614. break;
  2615. }
  2616. lock.unlock();
  2617. size_t last = std::min(nelements, first + chunk_size);
  2618. if (local_hist.empty()) {
  2619. local_hist.resize(hist_cur.size(), 0);
  2620. }
  2621. local_size += ggml_quantize_chunk(new_type, f32_data, new_data, first, last - first, local_hist.data());
  2622. }
  2623. };
  2624. if ((int) workers.size() < nthread_use - 1) {
  2625. workers.resize(nthread_use - 1);
  2626. }
  2627. for (int it = 0; it < nthread_use - 1; ++it) {
  2628. workers[it] = std::thread(compute);
  2629. }
  2630. compute();
  2631. for (int it = 0; it < nthread_use - 1; ++it) {
  2632. workers[it].join();
  2633. }
  2634. }
  2635. printf("size = %8.2f MB -> %8.2f MB | hist: ", tensor.size/1024.0/1024.0, new_size/1024.0/1024.0);
  2636. int64_t tot_count = 0;
  2637. for (size_t i = 0; i < hist_cur.size(); i++) {
  2638. hist_all[i] += hist_cur[i];
  2639. tot_count += hist_cur[i];
  2640. }
  2641. if (tot_count > 0) {
  2642. for (size_t i = 0; i < hist_cur.size(); i++) {
  2643. printf("%5.3f ", hist_cur[i] / float(nelements));
  2644. }
  2645. }
  2646. printf("\n");
  2647. }
  2648. total_size_org += tensor.size;
  2649. total_size_new += new_size;
  2650. file_saver.write_tensor(tensor, new_type, new_data, new_size);
  2651. }
  2652. printf("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  2653. printf("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  2654. {
  2655. int64_t sum_all = 0;
  2656. for (size_t i = 0; i < hist_all.size(); i++) {
  2657. sum_all += hist_all[i];
  2658. }
  2659. if (sum_all > 0) {
  2660. printf("%s: hist: ", __func__);
  2661. for (size_t i = 0; i < hist_all.size(); i++) {
  2662. printf("%5.3f ", hist_all[i] / float(sum_all));
  2663. }
  2664. printf("\n");
  2665. }
  2666. }
  2667. }
  2668. //
  2669. // interface implementation
  2670. //
  2671. struct llama_model * llama_load_model_from_file(
  2672. const char * path_model,
  2673. struct llama_context_params params) {
  2674. ggml_time_init();
  2675. llama_model * model = new llama_model;
  2676. ggml_type memory_type = params.f16_kv ? GGML_TYPE_F16 : GGML_TYPE_F32;
  2677. if (!llama_model_load(path_model, *model, model->vocab, params.n_ctx, params.n_batch, params.n_gqa, params.rms_norm_eps, params.n_gpu_layers,
  2678. params.main_gpu, params.tensor_split, params.mul_mat_q, params.rope_freq_base, params.rope_freq_scale,params.low_vram,
  2679. memory_type, params.use_mmap, params.use_mlock, params.vocab_only, params.progress_callback,
  2680. params.progress_callback_user_data)) {
  2681. delete model;
  2682. fprintf(stderr, "%s: failed to load model\n", __func__);
  2683. return nullptr;
  2684. }
  2685. return model;
  2686. }
  2687. void llama_free_model(struct llama_model * model) {
  2688. delete model;
  2689. }
  2690. struct llama_context * llama_new_context_with_model(
  2691. struct llama_model * model,
  2692. struct llama_context_params params) {
  2693. if (!model) {
  2694. return nullptr;
  2695. }
  2696. llama_context * ctx = new llama_context(*model);
  2697. if (params.seed == LLAMA_DEFAULT_SEED) {
  2698. params.seed = time(NULL);
  2699. }
  2700. unsigned cur_percentage = 0;
  2701. if (params.progress_callback == NULL) {
  2702. params.progress_callback_user_data = &cur_percentage;
  2703. params.progress_callback = [](float progress, void * ctx) {
  2704. unsigned * cur_percentage_p = (unsigned *) ctx;
  2705. unsigned percentage = (unsigned) (100 * progress);
  2706. while (percentage > *cur_percentage_p) {
  2707. *cur_percentage_p = percentage;
  2708. fprintf(stderr, ".");
  2709. fflush(stderr);
  2710. if (percentage >= 100) {
  2711. fprintf(stderr, "\n");
  2712. }
  2713. }
  2714. };
  2715. }
  2716. ctx->rng = std::mt19937(params.seed);
  2717. ctx->logits_all = params.logits_all;
  2718. ggml_type memory_type = params.f16_kv ? GGML_TYPE_F16 : GGML_TYPE_F32;
  2719. // reserve memory for context buffers
  2720. if (!params.vocab_only) {
  2721. if (!kv_cache_init(ctx->model.hparams, ctx->kv_self, memory_type, ctx->model.hparams.n_ctx, params.n_gpu_layers)) {
  2722. fprintf(stderr, "%s: kv_cache_init() failed for self-attention cache\n", __func__);
  2723. llama_free(ctx);
  2724. return nullptr;
  2725. }
  2726. {
  2727. const size_t memory_size = ggml_nbytes(ctx->kv_self.k) + ggml_nbytes(ctx->kv_self.v);
  2728. fprintf(stderr, "%s: kv self size = %7.2f MB\n", __func__, memory_size / 1024.0 / 1024.0);
  2729. }
  2730. const auto & hparams = ctx->model.hparams;
  2731. // resized during inference
  2732. if (params.logits_all) {
  2733. ctx->logits.reserve(hparams.n_ctx*hparams.n_vocab);
  2734. } else {
  2735. ctx->logits.reserve(hparams.n_vocab);
  2736. }
  2737. if (params.embedding){
  2738. ctx->embedding.resize(hparams.n_embd);
  2739. }
  2740. #ifdef LLAMA_USE_ALLOCATOR
  2741. {
  2742. static const size_t tensor_alignment = 32;
  2743. // the compute buffer is used to store the tensor and graph structs, while the allocator buffer is used for the tensor data
  2744. ctx->buf_compute.resize(ggml_tensor_overhead()*GGML_MAX_NODES + ggml_graph_overhead());
  2745. // create measure allocator
  2746. ctx->alloc = ggml_allocr_new_measure(tensor_alignment);
  2747. // build worst-case graph
  2748. int n_tokens = std::min((int)hparams.n_ctx, params.n_batch);
  2749. int n_past = hparams.n_ctx - n_tokens;
  2750. llama_token token = llama_token_bos(); // not actually used by llama_build_graph, but required to choose between token and embedding inputs graph
  2751. ggml_cgraph * gf = llama_build_graph(*ctx, &token, NULL, n_tokens, n_past);
  2752. // measure memory requirements for the graph
  2753. size_t alloc_size = ggml_allocr_alloc_graph(ctx->alloc, gf) + tensor_alignment;
  2754. fprintf(stderr, "%s: compute buffer total size = %7.2f MB\n", __func__, (ctx->buf_compute.size + alloc_size) / 1024.0 / 1024.0);
  2755. // debug - for comparison with scratch buffer
  2756. //size_t prev_req =
  2757. // MEM_REQ_SCRATCH0(hparams.n_ctx).at(ctx->model.type) +
  2758. // MEM_REQ_SCRATCH1().at(ctx->model.type) +
  2759. // MEM_REQ_EVAL().at(ctx->model.type);
  2760. //fprintf(stderr, "%s: (debug) equivalent with scratch buffer = %7.2f MB\n", __func__, prev_req / 1024.0 / 1024.0);
  2761. // recreate allocator with exact memory requirements
  2762. ggml_allocr_free(ctx->alloc);
  2763. ctx->buf_alloc.resize(alloc_size);
  2764. ctx->alloc = ggml_allocr_new(ctx->buf_alloc.addr, ctx->buf_alloc.size, tensor_alignment);
  2765. }
  2766. #else
  2767. ctx->buf_compute.resize(MEM_REQ_EVAL().at(ctx->model.type) + ggml_graph_overhead());
  2768. #endif
  2769. #ifdef LLAMA_USE_SCRATCH
  2770. ctx->buf_scratch[0].resize(MEM_REQ_SCRATCH0(hparams.n_ctx).at(ctx->model.type));
  2771. ctx->buf_scratch[1].resize(MEM_REQ_SCRATCH1().at(ctx->model.type));
  2772. #endif
  2773. }
  2774. #ifdef GGML_USE_METAL
  2775. if (params.n_gpu_layers > 0) {
  2776. // this allocates all Metal resources and memory buffers
  2777. ctx->ctx_metal = ggml_metal_init(1);
  2778. void * data_ptr = NULL;
  2779. size_t data_size = 0;
  2780. if (params.use_mmap) {
  2781. data_ptr = ctx->model.mapping->addr;
  2782. data_size = ctx->model.mapping->size;
  2783. } else {
  2784. data_ptr = ggml_get_mem_buffer(ctx->model.ctx);
  2785. data_size = ggml_get_mem_size (ctx->model.ctx);
  2786. }
  2787. const size_t max_size = ggml_get_max_tensor_size(ctx->model.ctx);
  2788. fprintf(stderr, "%s: max tensor size = %8.2f MB\n", __func__, max_size/1024.0/1024.0);
  2789. #define LLAMA_METAL_CHECK_BUF(result) \
  2790. if (!(result)) { \
  2791. fprintf(stderr, "%s: failed to add buffer\n", __func__); \
  2792. llama_free(ctx); \
  2793. return NULL; \
  2794. }
  2795. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "data", data_ptr, data_size, max_size));
  2796. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "eval", ctx->buf_compute.addr, ctx->buf_compute.size, 0));
  2797. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "kv", ctx->kv_self.buf.addr, ctx->kv_self.buf.size, 0));
  2798. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "scr0", ctx->buf_scratch[0].addr, ctx->buf_scratch[0].size, 0));
  2799. LLAMA_METAL_CHECK_BUF(ggml_metal_add_buffer(ctx->ctx_metal, "scr1", ctx->buf_scratch[1].addr, ctx->buf_scratch[1].size, 0));
  2800. #undef LLAMA_METAL_CHECK_BUF
  2801. }
  2802. #endif
  2803. #ifdef GGML_USE_MPI
  2804. ctx->ctx_mpi = ggml_mpi_init();
  2805. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  2806. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  2807. const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos());
  2808. while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  2809. llama_backend_free();
  2810. exit(1);
  2811. }
  2812. #endif
  2813. return ctx;
  2814. }
  2815. struct llama_context * llama_init_from_file(
  2816. const char * path_model,
  2817. struct llama_context_params params) {
  2818. struct llama_model * model = llama_load_model_from_file(path_model, params);
  2819. if (!model) {
  2820. return nullptr;
  2821. }
  2822. struct llama_context * ctx = llama_new_context_with_model(model, params);
  2823. ctx->model_owner = true;
  2824. return ctx;
  2825. }
  2826. void llama_free(struct llama_context * ctx) {
  2827. delete ctx;
  2828. }
  2829. int llama_model_quantize(
  2830. const char * fname_inp,
  2831. const char * fname_out,
  2832. const llama_model_quantize_params *params) {
  2833. try {
  2834. llama_model_quantize_internal(fname_inp, fname_out, params);
  2835. return 0;
  2836. } catch (const std::exception & err) {
  2837. fprintf(stderr, "%s: failed to quantize: %s\n", __func__, err.what());
  2838. return 1;
  2839. }
  2840. }
  2841. int llama_apply_lora_from_file_internal(const struct llama_model & model, const char * path_lora, const char * path_base_model, int n_threads) {
  2842. fprintf(stderr, "%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  2843. const int64_t t_start_lora_us = ggml_time_us();
  2844. auto fin = std::ifstream(path_lora, std::ios::binary);
  2845. if (!fin) {
  2846. fprintf(stderr, "%s: failed to open '%s'\n", __func__, path_lora);
  2847. return 1;
  2848. }
  2849. // verify magic and version
  2850. {
  2851. uint32_t magic;
  2852. fin.read((char *) &magic, sizeof(magic));
  2853. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  2854. fprintf(stderr, "%s: bad file magic\n", __func__);
  2855. return 1;
  2856. }
  2857. uint32_t format_version;
  2858. fin.read((char *) &format_version, sizeof(format_version));
  2859. if (format_version != 1) {
  2860. fprintf(stderr, "%s: unsupported file version\n", __func__ );
  2861. return 1;
  2862. }
  2863. }
  2864. int32_t lora_r;
  2865. int32_t lora_alpha;
  2866. fin.read((char *) &lora_r, sizeof(lora_r));
  2867. fin.read((char *) &lora_alpha, sizeof(lora_alpha));
  2868. float scaling = (float)lora_alpha / (float)lora_r;
  2869. fprintf(stderr, "%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  2870. // create a temporary ggml context to store the lora tensors
  2871. // todo: calculate size from biggest possible tensor
  2872. std::vector<uint8_t> lora_buf(1024ull * 1024ull * 1024ull);
  2873. struct ggml_init_params params;
  2874. params.mem_size = lora_buf.size();
  2875. params.mem_buffer = lora_buf.data();
  2876. params.no_alloc = false;
  2877. ggml_context * lora_ctx = ggml_init(params);
  2878. std::unordered_map<std::string, struct ggml_tensor *> lora_tensors;
  2879. // create a name -> tensor map of the model to accelerate lookups
  2880. std::unordered_map<std::string, struct ggml_tensor*> model_tensors;
  2881. for (const auto & kv: model.tensors_by_name) {
  2882. model_tensors.insert(kv);
  2883. }
  2884. // load base model
  2885. std::unique_ptr<llama_model_loader> model_loader;
  2886. ggml_context * base_ctx = NULL;
  2887. llama_buffer base_buf;
  2888. if (path_base_model) {
  2889. fprintf(stderr, "%s: loading base model from '%s'\n", __func__, path_base_model);
  2890. model_loader.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true));
  2891. size_t ctx_size;
  2892. size_t mmapped_size;
  2893. model_loader->calc_sizes(&ctx_size, &mmapped_size);
  2894. base_buf.resize(ctx_size);
  2895. ggml_init_params base_params;
  2896. base_params.mem_size = base_buf.size;
  2897. base_params.mem_buffer = base_buf.addr;
  2898. base_params.no_alloc = model_loader->use_mmap;
  2899. base_ctx = ggml_init(base_params);
  2900. model_loader->ggml_ctx = base_ctx;
  2901. // maybe this should in llama_model_loader
  2902. if (model_loader->use_mmap) {
  2903. model_loader->mapping.reset(new llama_mmap(&model_loader->file_loader->file, /* prefetch */ 0, ggml_is_numa()));
  2904. }
  2905. }
  2906. // read tensors and apply
  2907. bool warned = false;
  2908. int n_tensors = 0;
  2909. std::vector<uint8_t> work_buffer;
  2910. while (true) {
  2911. int32_t n_dims;
  2912. int32_t length;
  2913. int32_t ftype;
  2914. fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  2915. fin.read(reinterpret_cast<char *>(&length), sizeof(length));
  2916. fin.read(reinterpret_cast<char *>(&ftype), sizeof(ftype));
  2917. if (fin.eof()) {
  2918. break;
  2919. }
  2920. int32_t ne[2] = { 1, 1 };
  2921. for (int i = 0; i < n_dims; ++i) {
  2922. fin.read(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  2923. }
  2924. std::string name;
  2925. {
  2926. char buf[1024];
  2927. fin.read(buf, length);
  2928. name = std::string(buf, length);
  2929. }
  2930. // check for lora suffix and get the type of tensor
  2931. const std::string lora_suffix = ".lora";
  2932. size_t pos = name.rfind(lora_suffix);
  2933. if (pos == std::string::npos) {
  2934. fprintf(stderr, "%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  2935. return 1;
  2936. }
  2937. std::string lora_type = name.substr(pos + lora_suffix.length());
  2938. std::string base_name = name;
  2939. base_name.erase(pos);
  2940. // fprintf(stderr, "%s: %s => %s (lora type %s) ", __func__, name.c_str(),base_name.c_str(), lora_type.c_str());
  2941. if (model_tensors.find(base_name) == model_tensors.end()) {
  2942. fprintf(stderr, "%s: unknown tensor '%s' in lora adapter\n", __func__, name.data());
  2943. return 1;
  2944. }
  2945. // create ggml tensor
  2946. ggml_type wtype;
  2947. switch (ftype) {
  2948. case 0: wtype = GGML_TYPE_F32; break;
  2949. case 1: wtype = GGML_TYPE_F16; break;
  2950. default:
  2951. {
  2952. fprintf(stderr, "%s: invalid tensor data type '%d'\n",
  2953. __func__, ftype);
  2954. return false;
  2955. }
  2956. }
  2957. ggml_tensor * lora_tensor;
  2958. if (n_dims == 2) {
  2959. lora_tensor = ggml_new_tensor_2d(lora_ctx, wtype, ne[0], ne[1]);
  2960. }
  2961. else {
  2962. fprintf(stderr, "%s: unsupported tensor dimension %d\n", __func__, n_dims);
  2963. return 1;
  2964. }
  2965. ggml_set_name(lora_tensor, "lora_tensor");
  2966. // load tensor data
  2967. size_t offset = fin.tellg();
  2968. size_t tensor_data_size = ggml_nbytes(lora_tensor);
  2969. offset = (offset + 31) & -32;
  2970. fin.seekg(offset);
  2971. fin.read((char*)lora_tensor->data, tensor_data_size);
  2972. lora_tensors[name] = lora_tensor;
  2973. // check if we have both A and B tensors and apply
  2974. if (lora_tensors.find(base_name + ".loraA") != lora_tensors.end() &&
  2975. lora_tensors.find(base_name + ".loraB") != lora_tensors.end()) {
  2976. ggml_tensor * dest_t = model_tensors[base_name];
  2977. offload_func_t offload_func = llama_nop;
  2978. offload_func_t offload_func_force_inplace = llama_nop;
  2979. #ifdef GGML_USE_CUBLAS
  2980. if (dest_t->backend == GGML_BACKEND_GPU || dest_t->backend == GGML_BACKEND_GPU_SPLIT) {
  2981. if (dest_t->type != GGML_TYPE_F16) {
  2982. throw std::runtime_error(format(
  2983. "%s: error: the simultaneous use of LoRAs and GPU acceleration is only supported for f16 models", __func__));
  2984. }
  2985. offload_func = ggml_cuda_assign_buffers;
  2986. offload_func_force_inplace = ggml_cuda_assign_buffers_force_inplace;
  2987. }
  2988. #endif // GGML_USE_CUBLAS
  2989. ggml_tensor * base_t;
  2990. if (model_loader) {
  2991. // load from base model
  2992. if (model_loader->tensors_map.name_to_idx.find(base_name) == model_loader->tensors_map.name_to_idx.end()) {
  2993. fprintf(stderr, "%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  2994. return 1;
  2995. }
  2996. size_t idx = model_loader->tensors_map.name_to_idx[base_name];
  2997. llama_load_tensor & lt = model_loader->tensors_map.tensors[idx];
  2998. base_t = model_loader->get_tensor(base_name, { (uint32_t)dest_t->ne[0], (uint32_t)dest_t->ne[1] }, GGML_BACKEND_CPU);
  2999. lt.data = (uint8_t *) lt.ggml_tensor->data;
  3000. model_loader->load_data_for(lt);
  3001. lt.ggml_tensor->data = lt.data;
  3002. }
  3003. else {
  3004. base_t = dest_t;
  3005. }
  3006. if (ggml_is_quantized(base_t->type)) {
  3007. if (!warned) {
  3008. fprintf(stderr, "%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  3009. "use a f16 or f32 base model with --lora-base\n", __func__);
  3010. warned = true;
  3011. }
  3012. }
  3013. ggml_tensor * loraA = lora_tensors[base_name + ".loraA"];
  3014. GGML_ASSERT(loraA->type == GGML_TYPE_F32);
  3015. ggml_set_name(loraA, "loraA");
  3016. ggml_tensor * loraB = lora_tensors[base_name + ".loraB"];
  3017. GGML_ASSERT(loraB->type == GGML_TYPE_F32);
  3018. ggml_set_name(loraB, "loraB");
  3019. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  3020. fprintf(stderr, "%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  3021. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  3022. return 1;
  3023. }
  3024. // w = w + BA*s
  3025. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  3026. offload_func(BA);
  3027. ggml_set_name(BA, "BA");
  3028. if (scaling != 1.0f) {
  3029. ggml_tensor * scale_tensor = ggml_new_f32(lora_ctx, scaling);
  3030. ggml_set_name(scale_tensor, "scale_tensor");
  3031. BA = ggml_scale_inplace(lora_ctx, BA, scale_tensor);
  3032. offload_func(BA);
  3033. ggml_set_name(BA, "BA_scaled");
  3034. }
  3035. ggml_tensor * r;
  3036. if (base_t == dest_t) {
  3037. r = ggml_add_inplace(lora_ctx, dest_t, BA);
  3038. offload_func_force_inplace(r);
  3039. ggml_set_name(r, "r_add_inplace");
  3040. }
  3041. else {
  3042. r = ggml_add(lora_ctx, base_t, BA);
  3043. offload_func(r);
  3044. ggml_set_name(r, "r_add");
  3045. r = ggml_cpy(lora_ctx, r, dest_t);
  3046. offload_func(r);
  3047. ggml_set_name(r, "r_cpy");
  3048. }
  3049. struct ggml_cgraph gf = ggml_build_forward(r);
  3050. ggml_graph_compute_helper(work_buffer, &gf, n_threads);
  3051. // we won't need these tensors again, reset the context to save memory
  3052. ggml_free(lora_ctx);
  3053. lora_ctx = ggml_init(params);
  3054. lora_tensors.clear();
  3055. n_tensors++;
  3056. if (n_tensors % 4 == 0) {
  3057. fprintf(stderr, ".");
  3058. }
  3059. }
  3060. }
  3061. // TODO: this should be in a destructor, it will leak on failure
  3062. ggml_free(lora_ctx);
  3063. if (base_ctx) {
  3064. ggml_free(base_ctx);
  3065. }
  3066. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  3067. fprintf(stderr, " done (%.2f ms)\n", t_lora_us / 1000.0);
  3068. return 0;
  3069. }
  3070. int llama_apply_lora_from_file(struct llama_context * ctx, const char * path_lora, const char * path_base_model, int n_threads) {
  3071. try {
  3072. return llama_apply_lora_from_file_internal(ctx->model, path_lora, path_base_model, n_threads);
  3073. } catch (const std::exception & err) {
  3074. fprintf(stderr, "%s: failed to apply lora adapter: %s\n", __func__, err.what());
  3075. return 1;
  3076. }
  3077. }
  3078. int llama_model_apply_lora_from_file(const struct llama_model * model, const char * path_lora, const char * path_base_model, int n_threads) {
  3079. try {
  3080. return llama_apply_lora_from_file_internal(*model, path_lora, path_base_model, n_threads);
  3081. } catch (const std::exception & err) {
  3082. fprintf(stderr, "%s: failed to apply lora adapter: %s\n", __func__, err.what());
  3083. return 1;
  3084. }
  3085. }
  3086. int llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  3087. return ctx->kv_self.n;
  3088. }
  3089. #define LLAMA_MAX_RNG_STATE (64*1024)
  3090. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  3091. if (seed == LLAMA_DEFAULT_SEED) {
  3092. seed = time(NULL);
  3093. }
  3094. ctx->rng.seed(seed);
  3095. }
  3096. // Returns the *maximum* size of the state
  3097. size_t llama_get_state_size(const struct llama_context * ctx) {
  3098. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  3099. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  3100. const size_t s_rng_size = sizeof(size_t);
  3101. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  3102. const size_t s_logits_capacity = sizeof(size_t);
  3103. const size_t s_logits_size = sizeof(size_t);
  3104. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  3105. const size_t s_embedding_size = sizeof(size_t);
  3106. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  3107. const size_t s_kv_size = sizeof(size_t);
  3108. const size_t s_kv_ntok = sizeof(int);
  3109. const size_t s_kv = ctx->kv_self.buf.size;
  3110. const size_t s_total = (
  3111. + s_rng_size
  3112. + s_rng
  3113. + s_logits_capacity
  3114. + s_logits_size
  3115. + s_logits
  3116. + s_embedding_size
  3117. + s_embedding
  3118. + s_kv_size
  3119. + s_kv_ntok
  3120. + s_kv
  3121. );
  3122. return s_total;
  3123. }
  3124. /** copy state data into either a buffer or file depending on the passed in context
  3125. *
  3126. * file context:
  3127. * llama_file file("/path", "wb");
  3128. * llama_data_file_context data_ctx(&file);
  3129. * llama_copy_state_data(ctx, &data_ctx);
  3130. *
  3131. * buffer context:
  3132. * std::vector<uint8_t> buf(max_size, 0);
  3133. * llama_data_buffer_context data_ctx(&buf.data());
  3134. * llama_copy_state_data(ctx, &data_ctx);
  3135. *
  3136. */
  3137. void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  3138. // copy rng
  3139. {
  3140. std::stringstream rng_ss;
  3141. rng_ss << ctx->rng;
  3142. const size_t rng_size = rng_ss.str().size();
  3143. char rng_buf[LLAMA_MAX_RNG_STATE];
  3144. memset(&rng_buf[0], 0, LLAMA_MAX_RNG_STATE);
  3145. memcpy(&rng_buf[0], rng_ss.str().data(), rng_ss.str().size());
  3146. data_ctx->write(&rng_size, sizeof(rng_size));
  3147. data_ctx->write(&rng_buf[0], LLAMA_MAX_RNG_STATE);
  3148. }
  3149. // copy logits
  3150. {
  3151. const size_t logits_cap = ctx->logits.capacity();
  3152. const size_t logits_size = ctx->logits.size();
  3153. data_ctx->write(&logits_cap, sizeof(logits_cap));
  3154. data_ctx->write(&logits_size, sizeof(logits_size));
  3155. if (logits_size) {
  3156. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  3157. }
  3158. // If there is a gap between the size and the capacity, write padding
  3159. size_t padding_size = (logits_cap - logits_size) * sizeof(float);
  3160. if (padding_size > 0) {
  3161. std::vector<uint8_t> padding(padding_size, 0); // Create a buffer filled with zeros
  3162. data_ctx->write(padding.data(), padding_size);
  3163. }
  3164. }
  3165. // copy embeddings
  3166. {
  3167. const size_t embedding_size = ctx->embedding.size();
  3168. data_ctx->write(&embedding_size, sizeof(embedding_size));
  3169. if (embedding_size) {
  3170. data_ctx->write(ctx->embedding.data(), embedding_size * sizeof(float));
  3171. }
  3172. }
  3173. // copy kv cache
  3174. {
  3175. const auto & kv_self = ctx->kv_self;
  3176. const auto & hparams = ctx->model.hparams;
  3177. const int n_layer = hparams.n_layer;
  3178. const int n_embd = hparams.n_embd_gqa();
  3179. const int n_ctx = hparams.n_ctx;
  3180. const size_t kv_size = kv_self.buf.size;
  3181. const int kv_ntok = llama_get_kv_cache_token_count(ctx);
  3182. data_ctx->write(&kv_size, sizeof(kv_size));
  3183. data_ctx->write(&kv_ntok, sizeof(kv_ntok));
  3184. if (kv_size) {
  3185. const size_t elt_size = ggml_element_size(kv_self.k);
  3186. ggml_context * cpy_ctx = ggml_init({ 4096, NULL, /* no_alloc */ true });
  3187. ggml_cgraph gf{};
  3188. ggml_tensor * kout3d = ggml_new_tensor_3d(cpy_ctx, kv_self.k->type, n_embd, kv_ntok, n_layer);
  3189. std::vector<uint8_t> kout3d_data(ggml_nbytes(kout3d), 0);
  3190. kout3d->data = kout3d_data.data();
  3191. ggml_tensor * vout3d = ggml_new_tensor_3d(cpy_ctx, kv_self.v->type, kv_ntok, n_embd, n_layer);
  3192. std::vector<uint8_t> vout3d_data(ggml_nbytes(vout3d), 0);
  3193. vout3d->data = vout3d_data.data();
  3194. ggml_tensor * k3d = ggml_view_3d(cpy_ctx, kv_self.k,
  3195. n_embd, kv_ntok, n_layer,
  3196. elt_size*n_embd, elt_size*n_embd*n_ctx, 0);
  3197. ggml_tensor * v3d = ggml_view_3d(cpy_ctx, kv_self.v,
  3198. kv_ntok, n_embd, n_layer,
  3199. elt_size*n_ctx, elt_size*n_ctx*n_embd, 0);
  3200. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, k3d, kout3d));
  3201. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, v3d, vout3d));
  3202. ggml_graph_compute_helper(ctx->work_buffer, &gf, /*n_threads*/ 1);
  3203. ggml_free(cpy_ctx);
  3204. // our data is now in the kout3d_data and vout3d_data buffers
  3205. // write them to file
  3206. data_ctx->write(kout3d_data.data(), kout3d_data.size());
  3207. data_ctx->write(vout3d_data.data(), vout3d_data.size());
  3208. }
  3209. }
  3210. }
  3211. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  3212. llama_data_buffer_context data_ctx(dst);
  3213. llama_copy_state_data_internal(ctx, &data_ctx);
  3214. return data_ctx.get_size_written();
  3215. }
  3216. // Sets the state reading from the specified source address
  3217. size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src) {
  3218. uint8_t * inp = src;
  3219. // set rng
  3220. {
  3221. size_t rng_size;
  3222. char rng_buf[LLAMA_MAX_RNG_STATE];
  3223. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  3224. memcpy(&rng_buf[0], inp, LLAMA_MAX_RNG_STATE); inp += LLAMA_MAX_RNG_STATE;
  3225. std::stringstream rng_ss;
  3226. rng_ss.str(std::string(&rng_buf[0], rng_size));
  3227. rng_ss >> ctx->rng;
  3228. LLAMA_ASSERT(rng_ss.fail() == false);
  3229. }
  3230. // set logits
  3231. {
  3232. size_t logits_cap;
  3233. size_t logits_size;
  3234. memcpy(&logits_cap, inp, sizeof(logits_cap)); inp += sizeof(logits_cap);
  3235. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  3236. LLAMA_ASSERT(ctx->logits.capacity() == logits_cap);
  3237. if (logits_size) {
  3238. ctx->logits.resize(logits_size);
  3239. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  3240. }
  3241. inp += logits_cap * sizeof(float);
  3242. }
  3243. // set embeddings
  3244. {
  3245. size_t embedding_size;
  3246. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  3247. LLAMA_ASSERT(ctx->embedding.capacity() == embedding_size);
  3248. if (embedding_size) {
  3249. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  3250. inp += embedding_size * sizeof(float);
  3251. }
  3252. }
  3253. // set kv cache
  3254. {
  3255. const auto & kv_self = ctx->kv_self;
  3256. const auto & hparams = ctx->model.hparams;
  3257. const int n_layer = hparams.n_layer;
  3258. const int n_embd = hparams.n_embd_gqa();
  3259. const int n_ctx = hparams.n_ctx;
  3260. size_t kv_size;
  3261. int kv_ntok;
  3262. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  3263. memcpy(&kv_ntok, inp, sizeof(kv_ntok)); inp += sizeof(kv_ntok);
  3264. if (kv_size) {
  3265. LLAMA_ASSERT(kv_self.buf.size == kv_size);
  3266. const size_t elt_size = ggml_element_size(kv_self.k);
  3267. ggml_context * cpy_ctx = ggml_init({ 4096, NULL, /* no_alloc */ true });
  3268. ggml_cgraph gf{};
  3269. ggml_tensor * kin3d = ggml_new_tensor_3d(cpy_ctx, kv_self.k->type, n_embd, kv_ntok, n_layer);
  3270. kin3d->data = (void *) inp;
  3271. inp += ggml_nbytes(kin3d);
  3272. ggml_tensor * vin3d = ggml_new_tensor_3d(cpy_ctx, kv_self.v->type, kv_ntok, n_embd, n_layer);
  3273. vin3d->data = (void *) inp;
  3274. inp += ggml_nbytes(vin3d);
  3275. ggml_tensor * k3d = ggml_view_3d(cpy_ctx, kv_self.k,
  3276. n_embd, kv_ntok, n_layer,
  3277. elt_size*n_embd, elt_size*n_embd*n_ctx, 0);
  3278. ggml_tensor * v3d = ggml_view_3d(cpy_ctx, kv_self.v,
  3279. kv_ntok, n_embd, n_layer,
  3280. elt_size*n_ctx, elt_size*n_ctx*n_embd, 0);
  3281. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, kin3d, k3d));
  3282. ggml_build_forward_expand(&gf, ggml_cpy(cpy_ctx, vin3d, v3d));
  3283. ggml_graph_compute_helper(ctx->work_buffer, &gf, /*n_threads*/ 1);
  3284. ggml_free(cpy_ctx);
  3285. }
  3286. ctx->kv_self.n = kv_ntok;
  3287. }
  3288. const size_t nread = inp - src;
  3289. const size_t max_size = llama_get_state_size(ctx);
  3290. LLAMA_ASSERT(nread <= max_size);
  3291. return nread;
  3292. }
  3293. 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) {
  3294. llama_file file(path_session, "rb");
  3295. // sanity checks
  3296. {
  3297. const uint32_t magic = file.read_u32();
  3298. const uint32_t version = file.read_u32();
  3299. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  3300. fprintf(stderr, "%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  3301. return false;
  3302. }
  3303. llama_hparams session_hparams;
  3304. file.read_raw(&session_hparams, sizeof(llama_hparams));
  3305. if (session_hparams != ctx->model.hparams) {
  3306. fprintf(stderr, "%s : model hparams didn't match from session file!\n", __func__);
  3307. return false;
  3308. }
  3309. }
  3310. // load the prompt
  3311. {
  3312. const uint32_t n_token_count = file.read_u32();
  3313. if (n_token_count > n_token_capacity) {
  3314. fprintf(stderr, "%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  3315. return false;
  3316. }
  3317. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  3318. *n_token_count_out = n_token_count;
  3319. }
  3320. // restore the context state
  3321. {
  3322. const size_t n_state_size_cur = file.size - file.tell();
  3323. const size_t n_state_size_max = llama_get_state_size(ctx);
  3324. if (n_state_size_cur > n_state_size_max) {
  3325. fprintf(stderr, "%s : the state size in session file is too big! max %zu, got %zu\n", __func__, n_state_size_max, n_state_size_cur);
  3326. return false;
  3327. }
  3328. std::vector<uint8_t> state_data(n_state_size_max);
  3329. file.read_raw(state_data.data(), n_state_size_cur);
  3330. llama_set_state_data(ctx, state_data.data());
  3331. }
  3332. return true;
  3333. }
  3334. 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) {
  3335. try {
  3336. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  3337. } catch (const std::exception & err) {
  3338. fprintf(stderr, "error loading session file: %s\n", err.what());
  3339. return false;
  3340. }
  3341. }
  3342. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  3343. llama_file file(path_session, "wb");
  3344. file.write_u32(LLAMA_SESSION_MAGIC);
  3345. file.write_u32(LLAMA_SESSION_VERSION);
  3346. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  3347. // save the prompt
  3348. file.write_u32((uint32_t) n_token_count);
  3349. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  3350. // save the context state using stream saving
  3351. llama_data_file_context data_ctx(&file);
  3352. llama_copy_state_data_internal(ctx, &data_ctx);
  3353. return true;
  3354. }
  3355. int llama_eval(
  3356. struct llama_context * ctx,
  3357. const llama_token * tokens,
  3358. int n_tokens,
  3359. int n_past,
  3360. int n_threads) {
  3361. if (!llama_eval_internal(*ctx, tokens, nullptr, n_tokens, n_past, n_threads, nullptr)) {
  3362. fprintf(stderr, "%s: failed to eval\n", __func__);
  3363. return 1;
  3364. }
  3365. // get a more accurate load time, upon first eval
  3366. // TODO: fix this
  3367. if (!ctx->has_evaluated_once) {
  3368. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  3369. ctx->has_evaluated_once = true;
  3370. }
  3371. return 0;
  3372. }
  3373. int llama_eval_embd(
  3374. struct llama_context * ctx,
  3375. const float * embd,
  3376. int n_tokens,
  3377. int n_past,
  3378. int n_threads) {
  3379. if (!llama_eval_internal(*ctx, nullptr, embd, n_tokens, n_past, n_threads, nullptr)) {
  3380. fprintf(stderr, "%s: failed to eval\n", __func__);
  3381. return 1;
  3382. }
  3383. // get a more accurate load time, upon first eval
  3384. // TODO: fix this
  3385. if (!ctx->has_evaluated_once) {
  3386. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  3387. ctx->has_evaluated_once = true;
  3388. }
  3389. return 0;
  3390. }
  3391. int llama_eval_export(struct llama_context * ctx, const char * fname) {
  3392. const int n_batch = 1;
  3393. const int n_ctx = 512 - n_batch;
  3394. const std::vector<llama_token> tmp(n_batch, llama_token_bos());
  3395. if (!llama_eval_internal(*ctx, tmp.data(), nullptr, tmp.size(), n_ctx, 1, fname)) {
  3396. fprintf(stderr, "%s: failed to eval\n", __func__);
  3397. return 1;
  3398. }
  3399. return 0;
  3400. }
  3401. int llama_tokenize_with_model(
  3402. const struct llama_model * model,
  3403. const char * text,
  3404. llama_token * tokens,
  3405. int n_max_tokens,
  3406. bool add_bos) {
  3407. auto res = llama_tokenize(model->vocab, text, add_bos);
  3408. if (n_max_tokens < (int) res.size()) {
  3409. fprintf(stderr, "%s: too many tokens\n", __func__);
  3410. return -((int) res.size());
  3411. }
  3412. for (size_t i = 0; i < res.size(); i++) {
  3413. tokens[i] = res[i];
  3414. }
  3415. return res.size();
  3416. }
  3417. int llama_tokenize(
  3418. struct llama_context * ctx,
  3419. const char * text,
  3420. llama_token * tokens,
  3421. int n_max_tokens,
  3422. bool add_bos) {
  3423. return llama_tokenize_with_model(&ctx->model, text, tokens, n_max_tokens, add_bos);
  3424. }
  3425. int llama_n_vocab_from_model(const struct llama_model * model) {
  3426. return model->vocab.id_to_token.size();
  3427. }
  3428. int llama_n_ctx_from_model(const struct llama_model * model) {
  3429. return model->hparams.n_ctx;
  3430. }
  3431. int llama_n_embd_from_model(const struct llama_model * model) {
  3432. return model->hparams.n_embd;
  3433. }
  3434. int llama_n_vocab(const struct llama_context * ctx) {
  3435. return ctx->model.vocab.id_to_token.size();
  3436. }
  3437. int llama_n_ctx(const struct llama_context * ctx) {
  3438. return ctx->model.hparams.n_ctx;
  3439. }
  3440. int llama_n_embd(const struct llama_context * ctx) {
  3441. return ctx->model.hparams.n_embd;
  3442. }
  3443. int llama_get_vocab_from_model(
  3444. const struct llama_model * model,
  3445. const char * * strings,
  3446. float * scores,
  3447. int capacity) {
  3448. int n = std::min(capacity, (int) model->vocab.id_to_token.size());
  3449. for (int i = 0; i<n; ++i) {
  3450. strings[i] = model->vocab.id_to_token[i].tok.c_str();
  3451. scores[i] = model->vocab.id_to_token[i].score;
  3452. }
  3453. return n;
  3454. }
  3455. int llama_get_vocab(
  3456. const struct llama_context * ctx,
  3457. const char * * strings,
  3458. float * scores,
  3459. int capacity) {
  3460. return llama_get_vocab_from_model(&ctx->model, strings, scores, capacity);
  3461. }
  3462. float * llama_get_logits(struct llama_context * ctx) {
  3463. return ctx->logits.data();
  3464. }
  3465. float * llama_get_embeddings(struct llama_context * ctx) {
  3466. return ctx->embedding.data();
  3467. }
  3468. const char * llama_token_to_str_with_model(const struct llama_model * model, llama_token token) {
  3469. if (token >= llama_n_vocab_from_model(model)) {
  3470. return nullptr;
  3471. }
  3472. return model->vocab.id_to_token[token].tok.c_str();
  3473. }
  3474. const char * llama_token_to_str(const struct llama_context * ctx, llama_token token) {
  3475. return llama_token_to_str_with_model(&ctx->model, token);
  3476. }
  3477. llama_token llama_token_bos() {
  3478. return 1;
  3479. }
  3480. llama_token llama_token_eos() {
  3481. return 2;
  3482. }
  3483. llama_token llama_token_nl() {
  3484. return 13;
  3485. }
  3486. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  3487. struct llama_timings result = {
  3488. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  3489. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  3490. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  3491. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  3492. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  3493. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  3494. /*.n_sample =*/ std::max(1, ctx->n_sample),
  3495. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  3496. /*.n_eval =*/ std::max(1, ctx->n_eval),
  3497. };
  3498. return result;
  3499. }
  3500. void llama_print_timings(struct llama_context * ctx) {
  3501. const llama_timings timings = llama_get_timings(ctx);
  3502. fprintf(stderr, "\n");
  3503. fprintf(stderr, "%s: load time = %8.2f ms\n", __func__, timings.t_load_ms);
  3504. fprintf(stderr, "%s: sample time = %8.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  3505. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  3506. fprintf(stderr, "%s: prompt eval time = %8.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  3507. __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);
  3508. fprintf(stderr, "%s: eval time = %8.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  3509. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  3510. fprintf(stderr, "%s: total time = %8.2f ms\n", __func__, (timings.t_end_ms - timings.t_start_ms));
  3511. }
  3512. void llama_reset_timings(struct llama_context * ctx) {
  3513. ctx->t_start_us = ggml_time_us();
  3514. ctx->t_sample_us = ctx->n_sample = 0;
  3515. ctx->t_eval_us = ctx->n_eval = 0;
  3516. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  3517. }
  3518. const char * llama_print_system_info(void) {
  3519. static std::string s;
  3520. s = "";
  3521. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  3522. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  3523. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  3524. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  3525. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  3526. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  3527. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  3528. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  3529. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  3530. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  3531. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  3532. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  3533. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  3534. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  3535. return s.c_str();
  3536. }
  3537. // For internal test use
  3538. const std::vector<std::pair<std::string, struct ggml_tensor *>>& llama_internal_get_tensor_map(struct llama_context * ctx) {
  3539. return ctx->model.tensors_by_name;
  3540. }