llama.cpp 128 KB

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