llama.cpp 123 KB

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