llama.cpp 143 KB

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