llama.cpp 96 KB

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