llama.cpp 124 KB

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