llama.cpp 124 KB

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