llama.cpp 122 KB

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