llama.cpp 116 KB

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