llama.cpp 151 KB

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