1
0

llama.cpp 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848
  1. #include "llama.h"
  2. #include "ggml.h"
  3. #include <cinttypes>
  4. #include <fstream>
  5. #include <random>
  6. #include <map>
  7. #include <unordered_map>
  8. #include <queue>
  9. #include <regex>
  10. #include <cassert>
  11. #include <cstring>
  12. #define LLAMA_USE_SCRATCH
  13. #define LLAMA_MAX_SCRATCH_BUFFERS 16
  14. #define LLAMA_ASSERT(x) \
  15. do { \
  16. if (!(x)) { \
  17. fprintf(stderr, "LLAMA_ASSERT: %s:%d: %s\n", __FILE__, __LINE__, #x); \
  18. abort(); \
  19. } \
  20. } while (0)
  21. // determine number of model parts based on the dimension
  22. static const std::unordered_map<int, int> LLAMA_N_PARTS = {
  23. { 4096, 1 },
  24. { 5120, 2 },
  25. { 6656, 4 },
  26. { 8192, 8 },
  27. };
  28. // available llama models
  29. enum e_model {
  30. MODEL_UNKNOWN,
  31. MODEL_7B,
  32. MODEL_13B,
  33. MODEL_30B,
  34. MODEL_65B,
  35. };
  36. static const size_t MB = 1024*1024;
  37. // computed for n_ctx == 2048
  38. // TODO: dynamically determine these sizes
  39. // needs modifications in ggml
  40. static const std::map<e_model, size_t> MEM_REQ_SCRATCH0 = {
  41. { MODEL_7B, 512ull*MB },
  42. { MODEL_13B, 512ull*MB },
  43. { MODEL_30B, 512ull*MB },
  44. { MODEL_65B, 512ull*MB },
  45. };
  46. static const std::map<e_model, size_t> MEM_REQ_SCRATCH1 = {
  47. { MODEL_7B, 512ull*MB },
  48. { MODEL_13B, 512ull*MB },
  49. { MODEL_30B, 512ull*MB },
  50. { MODEL_65B, 512ull*MB },
  51. };
  52. // 2*n_embd*n_ctx*n_layer*sizeof(float16)
  53. static const std::map<e_model, size_t> MEM_REQ_KV_SELF = {
  54. { MODEL_7B, 1026ull*MB },
  55. { MODEL_13B, 1608ull*MB },
  56. { MODEL_30B, 3124ull*MB },
  57. { MODEL_65B, 5120ull*MB },
  58. };
  59. // this is mostly needed for temporary mul_mat buffers to dequantize the data
  60. // not actually needed if BLAS is disabled
  61. static const std::map<e_model, size_t> MEM_REQ_EVAL = {
  62. { MODEL_7B, 768ull*MB },
  63. { MODEL_13B, 1024ull*MB },
  64. { MODEL_30B, 1280ull*MB },
  65. { MODEL_65B, 1536ull*MB },
  66. };
  67. // default hparams (LLaMA 7B)
  68. struct llama_hparams {
  69. int32_t n_vocab = 32000;
  70. int32_t n_ctx = 512; // this is provided as user input?
  71. int32_t n_embd = 4096;
  72. int32_t n_mult = 256;
  73. int32_t n_head = 32;
  74. int32_t n_layer = 32;
  75. int32_t n_rot = 64;
  76. int32_t f16 = 1;
  77. };
  78. struct llama_layer {
  79. // normalization
  80. struct ggml_tensor * attention_norm;
  81. // attention
  82. struct ggml_tensor * wq;
  83. struct ggml_tensor * wk;
  84. struct ggml_tensor * wv;
  85. struct ggml_tensor * wo;
  86. // normalization
  87. struct ggml_tensor * ffn_norm;
  88. // ff
  89. struct ggml_tensor * w1;
  90. struct ggml_tensor * w2;
  91. struct ggml_tensor * w3;
  92. };
  93. struct llama_kv_cache {
  94. struct ggml_tensor * k;
  95. struct ggml_tensor * v;
  96. struct ggml_context * ctx;
  97. std::vector<uint8_t> buf;
  98. int n; // number of tokens currently in the cache
  99. };
  100. struct llama_model {
  101. e_model type = MODEL_UNKNOWN;
  102. llama_hparams hparams;
  103. struct ggml_tensor * tok_embeddings;
  104. struct ggml_tensor * norm;
  105. struct ggml_tensor * output;
  106. std::vector<llama_layer> layers;
  107. // context
  108. struct ggml_context * ctx;
  109. // key + value cache for the self attention
  110. // TODO: move to llama_state
  111. struct llama_kv_cache kv_self;
  112. // the model memory buffer
  113. std::vector<uint8_t> buf;
  114. // tensors
  115. int n_loaded;
  116. std::unordered_map<std::string, struct ggml_tensor *> tensors;
  117. };
  118. struct llama_vocab {
  119. using id = int32_t;
  120. using token = std::string;
  121. struct token_score {
  122. token tok;
  123. float score;
  124. };
  125. std::unordered_map<token, id> token_to_id;
  126. std::vector<token_score> id_to_token;
  127. };
  128. struct llama_context {
  129. std::mt19937 rng;
  130. int64_t t_load_us = 0;
  131. int64_t t_start_us = 0;
  132. int64_t t_sample_us = 0;
  133. int64_t t_eval_us = 0;
  134. int32_t n_sample = 0; // number of tokens sampled
  135. int32_t n_eval = 0; // number of eval calls
  136. llama_model model;
  137. llama_vocab vocab;
  138. size_t mem_per_token = 0;
  139. // decode output (2-dimensional array: [n_tokens][n_vocab])
  140. std::vector<float> logits;
  141. bool logits_all = false;
  142. // input embedding (1-dimensional array: [n_embd])
  143. std::vector<float> embedding;
  144. // memory buffers used to evaluate the model
  145. // TODO: move in llama_state
  146. std::vector<uint8_t> buf_compute;
  147. std::vector<uint8_t> buf_scratch[LLAMA_MAX_SCRATCH_BUFFERS];
  148. int buf_last = 0;
  149. size_t buf_max_size[LLAMA_MAX_SCRATCH_BUFFERS] = { 0 };
  150. void use_buf(struct ggml_context * ctx, int i) {
  151. #if defined(LLAMA_USE_SCRATCH)
  152. size_t last_size = 0;
  153. if (i == -1) {
  154. last_size = ggml_set_scratch(ctx, { 0, 0, nullptr, });
  155. } else {
  156. auto & buf = buf_scratch[i];
  157. last_size = ggml_set_scratch(ctx, { 0, buf.size(), buf.data(), });
  158. }
  159. if (buf_last >= 0) {
  160. buf_max_size[buf_last] = std::max(buf_max_size[buf_last], last_size);
  161. }
  162. buf_last = i;
  163. #else
  164. (void) i;
  165. (void) ctx;
  166. #endif
  167. }
  168. size_t get_buf_max_mem(int i) const {
  169. #if defined(LLAMA_USE_SCRATCH)
  170. return buf_max_size[i];
  171. #else
  172. (void) i;
  173. return 0;
  174. #endif
  175. }
  176. };
  177. //
  178. // kv cache
  179. //
  180. static bool kv_cache_init(
  181. const struct llama_hparams & hparams,
  182. struct llama_kv_cache & cache,
  183. ggml_type wtype,
  184. int n_ctx) {
  185. const int n_embd = hparams.n_embd;
  186. const int n_layer = hparams.n_layer;
  187. const int n_mem = n_layer*n_ctx;
  188. const int n_elements = n_embd*n_mem;
  189. cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
  190. struct ggml_init_params params;
  191. params.mem_size = cache.buf.size();
  192. params.mem_buffer = cache.buf.data();
  193. cache.ctx = ggml_init(params);
  194. if (!cache.ctx) {
  195. fprintf(stderr, "%s: failed to allocate memory for kv cache\n", __func__);
  196. return false;
  197. }
  198. cache.k = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  199. cache.v = ggml_new_tensor_1d(cache.ctx, wtype, n_elements);
  200. return true;
  201. }
  202. static void kv_cache_free(struct llama_kv_cache & cache) {
  203. if (cache.ctx) {
  204. ggml_free(cache.ctx);
  205. cache.ctx = nullptr;
  206. }
  207. }
  208. struct llama_context_params llama_context_default_params() {
  209. struct llama_context_params result = {
  210. /*.n_ctx =*/ 512,
  211. /*.n_parts =*/ -1,
  212. /*.seed =*/ 0,
  213. /*.f16_kv =*/ false,
  214. /*.logits_all =*/ false,
  215. /*.vocab_only =*/ false,
  216. /*.use_mlock =*/ false,
  217. /*.embedding =*/ false,
  218. /*.progress_callback =*/ nullptr,
  219. /*.progress_callback_user_data =*/ nullptr,
  220. };
  221. return result;
  222. }
  223. //
  224. // model loading
  225. //
  226. static bool llama_model_load(
  227. const std::string & fname,
  228. llama_context & lctx,
  229. int n_ctx,
  230. int n_parts,
  231. ggml_type memory_type,
  232. bool vocab_only,
  233. llama_progress_callback progress_callback,
  234. void *progress_callback_user_data) {
  235. fprintf(stderr, "%s: loading model from '%s' - please wait ...\n", __func__, fname.c_str());
  236. const int64_t t_start_us = ggml_time_us();
  237. lctx.t_start_us = t_start_us;
  238. std::vector<char> f_buf(1024*1024);
  239. auto & model = lctx.model;
  240. auto & vocab = lctx.vocab;
  241. auto fin = std::ifstream(fname, std::ios::binary);
  242. fin.rdbuf()->pubsetbuf(f_buf.data(), f_buf.size());
  243. if (!fin) {
  244. fprintf(stderr, "%s: failed to open '%s'\n", __func__, fname.c_str());
  245. return false;
  246. }
  247. // verify magic
  248. {
  249. uint32_t magic;
  250. fin.read((char *) &magic, sizeof(magic));
  251. if (magic == LLAMA_FILE_MAGIC_UNVERSIONED) {
  252. fprintf(stderr, "%s: invalid model file '%s' (too old, regenerate your model files!)\n",
  253. __func__, fname.c_str());
  254. return false;
  255. }
  256. if (magic != LLAMA_FILE_MAGIC) {
  257. fprintf(stderr, "%s: invalid model file '%s' (bad magic)\n", __func__, fname.c_str());
  258. return false;
  259. }
  260. uint32_t format_version;
  261. fin.read((char *) &format_version, sizeof(format_version));
  262. if (format_version != LLAMA_FILE_VERSION) {
  263. fprintf(stderr, "%s: invalid model file '%s' (unsupported format version %" PRIu32 ", expected %d)\n",
  264. __func__, fname.c_str(), format_version, LLAMA_FILE_VERSION);
  265. return false;
  266. }
  267. }
  268. int n_ff = 0;
  269. // load hparams
  270. {
  271. auto & hparams = model.hparams;
  272. fin.read((char *) &hparams.n_vocab, sizeof(hparams.n_vocab));
  273. //fin.read((char *) &hparams.n_ctx, sizeof(hparams.n_ctx));
  274. fin.read((char *) &hparams.n_embd, sizeof(hparams.n_embd));
  275. fin.read((char *) &hparams.n_mult, sizeof(hparams.n_mult));
  276. fin.read((char *) &hparams.n_head, sizeof(hparams.n_head));
  277. fin.read((char *) &hparams.n_layer, sizeof(hparams.n_layer));
  278. fin.read((char *) &hparams.n_rot, sizeof(hparams.n_rot));
  279. fin.read((char *) &hparams.f16, sizeof(hparams.f16));
  280. hparams.n_ctx = n_ctx;
  281. n_ff = ((2*(4*hparams.n_embd)/3 + hparams.n_mult - 1)/hparams.n_mult)*hparams.n_mult;
  282. if (n_parts < 1) {
  283. n_parts = LLAMA_N_PARTS.at(hparams.n_embd);
  284. }
  285. // temp warning to tell the user to use "--n_parts"
  286. if (hparams.f16 == 4 && n_parts != 1) {
  287. fprintf(stderr, "%s: GPTQ model detected - are you sure n_parts should be %d? we normally expect it to be 1\n", __func__, n_parts);
  288. fprintf(stderr, "%s: use '--n_parts 1' if necessary\n", __func__);
  289. }
  290. if (hparams.n_layer == 32) {
  291. model.type = e_model::MODEL_7B;
  292. }
  293. if (hparams.n_layer == 40) {
  294. model.type = e_model::MODEL_13B;
  295. }
  296. if (hparams.n_layer == 60) {
  297. model.type = e_model::MODEL_30B;
  298. }
  299. if (hparams.n_layer == 80) {
  300. model.type = e_model::MODEL_65B;
  301. }
  302. fprintf(stderr, "%s: n_vocab = %d\n", __func__, hparams.n_vocab);
  303. fprintf(stderr, "%s: n_ctx = %d\n", __func__, hparams.n_ctx);
  304. fprintf(stderr, "%s: n_embd = %d\n", __func__, hparams.n_embd);
  305. fprintf(stderr, "%s: n_mult = %d\n", __func__, hparams.n_mult);
  306. fprintf(stderr, "%s: n_head = %d\n", __func__, hparams.n_head);
  307. fprintf(stderr, "%s: n_layer = %d\n", __func__, hparams.n_layer);
  308. fprintf(stderr, "%s: n_rot = %d\n", __func__, hparams.n_rot);
  309. fprintf(stderr, "%s: f16 = %d\n", __func__, hparams.f16);
  310. fprintf(stderr, "%s: n_ff = %d\n", __func__, n_ff);
  311. fprintf(stderr, "%s: n_parts = %d\n", __func__, n_parts);
  312. fprintf(stderr, "%s: type = %d\n", __func__, model.type);
  313. }
  314. // load vocab
  315. {
  316. std::string word;
  317. vocab.id_to_token.resize(model.hparams.n_vocab);
  318. std::vector<char> tmp(64);
  319. for (int i = 0; i < model.hparams.n_vocab; i++) {
  320. uint32_t len;
  321. fin.read((char *) &len, sizeof(len));
  322. word.resize(len);
  323. if (len > 0) {
  324. tmp.resize(len);
  325. fin.read(tmp.data(), len);
  326. word.assign(tmp.data(), len);
  327. } else {
  328. word.clear();
  329. }
  330. float score;
  331. fin.read((char *) &score, sizeof(score));
  332. vocab.token_to_id[word] = i;
  333. auto &tok_score = vocab.id_to_token[i];
  334. tok_score.tok = word;
  335. tok_score.score = score;
  336. }
  337. }
  338. if (vocab_only) {
  339. return true;
  340. }
  341. // for the big tensors, we have the option to store the data in 16-bit floats or quantized
  342. // in order to save memory and also to speed up the computation
  343. // wtype is for per-layer weights, while vtype is for other weights
  344. ggml_type wtype, vtype;
  345. switch (model.hparams.f16) {
  346. case 0: wtype = vtype = GGML_TYPE_F32; break;
  347. case 1: wtype = vtype = GGML_TYPE_F16; break;
  348. case 2: wtype = vtype = GGML_TYPE_Q4_0; break;
  349. case 3: wtype = vtype = GGML_TYPE_Q4_1; break;
  350. case 4: wtype = GGML_TYPE_Q4_1; vtype = GGML_TYPE_F16; break;
  351. default:
  352. {
  353. fprintf(stderr, "%s: invalid model file '%s' (bad f16 value %d)\n",
  354. __func__, fname.c_str(), model.hparams.f16);
  355. return false;
  356. }
  357. }
  358. auto & ctx = model.ctx;
  359. size_t ctx_size = 0;
  360. {
  361. const auto & hparams = model.hparams;
  362. const int n_embd = hparams.n_embd;
  363. const int n_layer = hparams.n_layer;
  364. const int n_ctx = hparams.n_ctx;
  365. const int n_vocab = hparams.n_vocab;
  366. ctx_size += n_embd*n_vocab*ggml_type_sizef(vtype); // tok_embeddings
  367. ctx_size += n_embd*ggml_type_sizef(GGML_TYPE_F32); // norm
  368. ctx_size += n_embd*n_vocab*ggml_type_sizef(vtype); // output
  369. ctx_size += n_layer*(n_embd*ggml_type_sizef(GGML_TYPE_F32)); // attention_norm
  370. ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // wq
  371. ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // wk
  372. ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // wv
  373. ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // wo
  374. ctx_size += n_layer*(n_embd*ggml_type_sizef(GGML_TYPE_F32)); // ffn_norm
  375. ctx_size += n_layer*(n_ff*n_embd*ggml_type_sizef(wtype)); // w1
  376. ctx_size += n_layer*(n_ff*n_embd*ggml_type_sizef(wtype)); // w2
  377. ctx_size += n_layer*(n_ff*n_embd*ggml_type_sizef(wtype)); // w3
  378. ctx_size += n_ctx*n_layer*n_embd*ggml_type_sizef(memory_type); // memory_k
  379. ctx_size += n_ctx*n_layer*n_embd*ggml_type_sizef(memory_type); // memory_v
  380. ctx_size += (5 + 10*n_layer)*256; // object overhead
  381. fprintf(stderr, "%s: ggml ctx size = %6.2f MB\n", __func__, ctx_size/(1024.0*1024.0));
  382. }
  383. // print memory requirements
  384. {
  385. const size_t scale = memory_type == GGML_TYPE_F32 ? 2 : 1;
  386. // this is the total memory required to run the inference
  387. const size_t mem_required =
  388. ctx_size +
  389. MEM_REQ_SCRATCH0.at(model.type) +
  390. MEM_REQ_SCRATCH1.at(model.type) +
  391. MEM_REQ_EVAL.at (model.type);
  392. // this is the memory required by one llama_state
  393. const size_t mem_required_state =
  394. scale*MEM_REQ_KV_SELF.at(model.type);
  395. fprintf(stderr, "%s: mem required = %7.2f MB (+ %7.2f MB per state)\n", __func__,
  396. mem_required / 1024.0 / 1024.0, mem_required_state / 1024.0 / 1024.0);
  397. }
  398. // create the ggml context
  399. {
  400. lctx.model.buf.resize(ctx_size);
  401. struct ggml_init_params params = {
  402. /*.mem_size =*/ lctx.model.buf.size(),
  403. /*.mem_buffer =*/ lctx.model.buf.data(),
  404. };
  405. model.ctx = ggml_init(params);
  406. if (!model.ctx) {
  407. fprintf(stderr, "%s: ggml_init() failed\n", __func__);
  408. return false;
  409. }
  410. }
  411. // prepare memory for the weights
  412. {
  413. const auto & hparams = model.hparams;
  414. const int n_embd = hparams.n_embd;
  415. const int n_layer = hparams.n_layer;
  416. const int n_vocab = hparams.n_vocab;
  417. model.layers.resize(n_layer);
  418. model.tok_embeddings = ggml_new_tensor_2d(ctx, vtype, n_embd, n_vocab);
  419. model.norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  420. model.output = ggml_new_tensor_2d(ctx, vtype, n_embd, n_vocab);
  421. // map by name
  422. model.tensors["tok_embeddings.weight"] = model.tok_embeddings;
  423. model.tensors["norm.weight"] = model.norm;
  424. model.tensors["output.weight"] = model.output;
  425. for (int i = 0; i < n_layer; ++i) {
  426. auto & layer = model.layers[i];
  427. layer.attention_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  428. layer.wq = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  429. layer.wk = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  430. layer.wv = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  431. layer.wo = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  432. layer.ffn_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  433. layer.w1 = ggml_new_tensor_2d(ctx, wtype, n_embd, n_ff);
  434. layer.w2 = ggml_new_tensor_2d(ctx, wtype, n_ff, n_embd);
  435. layer.w3 = ggml_new_tensor_2d(ctx, wtype, n_embd, n_ff);
  436. // map by name
  437. model.tensors["layers." + std::to_string(i) + ".attention_norm.weight"] = layer.attention_norm;
  438. model.tensors["layers." + std::to_string(i) + ".attention.wq.weight"] = layer.wq;
  439. model.tensors["layers." + std::to_string(i) + ".attention.wk.weight"] = layer.wk;
  440. model.tensors["layers." + std::to_string(i) + ".attention.wv.weight"] = layer.wv;
  441. model.tensors["layers." + std::to_string(i) + ".attention.wo.weight"] = layer.wo;
  442. model.tensors["layers." + std::to_string(i) + ".ffn_norm.weight"] = layer.ffn_norm;
  443. model.tensors["layers." + std::to_string(i) + ".feed_forward.w1.weight"] = layer.w1;
  444. model.tensors["layers." + std::to_string(i) + ".feed_forward.w2.weight"] = layer.w2;
  445. model.tensors["layers." + std::to_string(i) + ".feed_forward.w3.weight"] = layer.w3;
  446. }
  447. }
  448. const size_t file_offset = fin.tellg();
  449. fin.close();
  450. std::vector<uint8_t> tmp;
  451. if (progress_callback) {
  452. progress_callback(0.0, progress_callback_user_data);
  453. }
  454. for (int i = 0; i < n_parts; ++i) {
  455. const int part_id = i;
  456. //const int part_id = n_parts - i - 1;
  457. std::string fname_part = fname;
  458. if (i > 0) {
  459. fname_part += "." + std::to_string(i);
  460. }
  461. fprintf(stderr, "%s: loading model part %d/%d from '%s'\n", __func__, i+1, n_parts, fname_part.c_str());
  462. fin = std::ifstream(fname_part, std::ios::binary);
  463. fin.rdbuf()->pubsetbuf(f_buf.data(), f_buf.size());
  464. fin.seekg(0, fin.end);
  465. const size_t file_size = fin.tellg();
  466. fin.seekg(file_offset);
  467. // load weights
  468. {
  469. size_t total_size = 0;
  470. model.n_loaded = 0;
  471. fprintf(stderr, "%s: ", __func__);
  472. while (true) {
  473. int32_t n_dims;
  474. int32_t length;
  475. int32_t ftype;
  476. fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  477. fin.read(reinterpret_cast<char *>(&length), sizeof(length));
  478. fin.read(reinterpret_cast<char *>(&ftype), sizeof(ftype));
  479. if (fin.eof()) {
  480. break;
  481. }
  482. int32_t nelements = 1;
  483. int32_t ne[2] = { 1, 1 };
  484. for (int i = 0; i < n_dims; ++i) {
  485. fin.read(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  486. nelements *= ne[i];
  487. }
  488. std::string name(length, 0);
  489. fin.read(&name[0], length);
  490. if (model.tensors.find(name.data()) == model.tensors.end()) {
  491. fprintf(stderr, "%s: unknown tensor '%s' in model file\n", __func__, name.data());
  492. return false;
  493. }
  494. // split_type = 0: split by columns
  495. // split_type = 1: split by rows
  496. int split_type = 0;
  497. // split_type = 0:
  498. // regex:
  499. // - tok_embeddings.*
  500. // - layers.*.attention.wo.weight
  501. // - layers.*.feed_forward.w2.weight
  502. // split_type = 1:
  503. // regex:
  504. // - output.*
  505. // - layers.*.attention.wq.weight
  506. // - layers.*.attention.wk.weight
  507. // - layers.*.attention.wv.weight
  508. // - layers.*.feed_forward.w1.weight
  509. // - layers.*.feed_forward.w3.weight
  510. if (name.find("tok_embeddings") != std::string::npos) {
  511. split_type = 0;
  512. } else if (name.find("layers") != std::string::npos) {
  513. if (name.find("attention.wo.weight") != std::string::npos) {
  514. split_type = 0;
  515. } else if (name.find("feed_forward.w2.weight") != std::string::npos) {
  516. split_type = 0;
  517. } else {
  518. split_type = 1;
  519. }
  520. } else if (name.find("output") != std::string::npos) {
  521. split_type = 1;
  522. }
  523. auto tensor = model.tensors[name.data()];
  524. if (n_dims == 1) {
  525. if (ggml_nelements(tensor) != nelements) {
  526. fprintf(stderr, "%s: tensor '%s' has wrong size in model file\n", __func__, name.data());
  527. return false;
  528. }
  529. } else {
  530. if (ggml_nelements(tensor)/n_parts != nelements) {
  531. fprintf(stderr, "%s: tensor '%s' has wrong size in model file\n", __func__, name.data());
  532. return false;
  533. }
  534. }
  535. if (n_dims == 1) {
  536. if (tensor->ne[0] != ne[0] || tensor->ne[1] != ne[1]) {
  537. fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%d, %d], expected [%d, %d]\n",
  538. __func__, name.data(), tensor->ne[0], tensor->ne[1], ne[0], ne[1]);
  539. return false;
  540. }
  541. } else {
  542. if (split_type == 0) {
  543. if (tensor->ne[0]/n_parts != ne[0] || tensor->ne[1] != ne[1]) {
  544. fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%d, %d], expected [%d, %d]\n",
  545. __func__, name.data(), tensor->ne[0]/n_parts, tensor->ne[1], ne[0], ne[1]);
  546. return false;
  547. }
  548. } else {
  549. if (tensor->ne[0] != ne[0] || tensor->ne[1]/n_parts != ne[1]) {
  550. fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%d, %d], expected [%d, %d]\n",
  551. __func__, name.data(), tensor->ne[0], tensor->ne[1]/n_parts, ne[0], ne[1]);
  552. return false;
  553. }
  554. }
  555. }
  556. if (0) {
  557. static const char * ftype_str[] = { "f32", "f16", "q4_0", "q4_1", };
  558. fprintf(stderr, "%24s - [%5d, %5d], type = %6s, split = %d\n", name.data(), ne[0], ne[1], ftype_str[ftype], split_type);
  559. }
  560. size_t bpe = 0;
  561. switch (ftype) {
  562. case 0: bpe = ggml_type_size(GGML_TYPE_F32); break;
  563. case 1: bpe = ggml_type_size(GGML_TYPE_F16); break;
  564. case 2: bpe = ggml_type_size(GGML_TYPE_Q4_0); assert(ne[0] % 64 == 0); break;
  565. case 3: bpe = ggml_type_size(GGML_TYPE_Q4_1); assert(ne[0] % 64 == 0); break;
  566. default:
  567. {
  568. fprintf(stderr, "%s: unknown ftype %d in model file\n", __func__, ftype);
  569. return false;
  570. }
  571. };
  572. if (n_dims == 1 || n_parts == 1) {
  573. if ((nelements*bpe)/ggml_blck_size(tensor->type) != ggml_nbytes(tensor)) {
  574. fprintf(stderr, "%s: tensor '%s' has wrong size in model file: got %zu, expected %zu\n",
  575. __func__, name.data(), ggml_nbytes(tensor), nelements*bpe);
  576. return false;
  577. }
  578. if (part_id == 0) {
  579. fin.read(reinterpret_cast<char *>(tensor->data), ggml_nbytes(tensor));
  580. } else {
  581. fin.seekg(ggml_nbytes(tensor), std::ios::cur);
  582. }
  583. total_size += ggml_nbytes(tensor);
  584. } else {
  585. if ((nelements*bpe)/ggml_blck_size(tensor->type) != ggml_nbytes(tensor)/n_parts) {
  586. fprintf(stderr, "%s: tensor '%s' has wrong size in model file: got %zu, expected %zu\n",
  587. __func__, name.data(), ggml_nbytes(tensor)/n_parts, nelements*bpe);
  588. return false;
  589. }
  590. if (split_type == 0) {
  591. const int np0 = ne[0];
  592. const size_t row_size = (tensor->ne[0]/ggml_blck_size(tensor->type))*ggml_type_size(tensor->type);
  593. assert(row_size == tensor->nb[1]);
  594. for (int i1 = 0; i1 < ne[1]; ++i1) {
  595. const size_t offset_row = i1*row_size;
  596. const size_t offset = offset_row + ((part_id*np0)/ggml_blck_size(tensor->type))*ggml_type_size(tensor->type);
  597. fin.read(reinterpret_cast<char *>(tensor->data) + offset, row_size/n_parts);
  598. }
  599. } else {
  600. const int np1 = ne[1];
  601. const size_t row_size = (tensor->ne[0]/ggml_blck_size(tensor->type))*ggml_type_size(tensor->type);
  602. for (int i1 = 0; i1 < ne[1]; ++i1) {
  603. const size_t offset_row = (i1 + part_id*np1)*row_size;
  604. fin.read(reinterpret_cast<char *>(tensor->data) + offset_row, row_size);
  605. }
  606. }
  607. total_size += ggml_nbytes(tensor)/n_parts;
  608. }
  609. //fprintf(stderr, "%42s - [%5d, %5d], type = %6s, %6.2f MB\n", name.data(), ne[0], ne[1], ftype == 0 ? "float" : "f16", ggml_nbytes(tensor)/1024.0/1024.0);
  610. model.n_loaded++;
  611. // progress
  612. if (progress_callback) {
  613. double current_file_progress = double(size_t(fin.tellg()) - file_offset) / double(file_size - file_offset);
  614. double current_progress = (double(i) + current_file_progress) / double(n_parts);
  615. progress_callback(current_progress, progress_callback_user_data);
  616. }
  617. if (model.n_loaded % 8 == 0) {
  618. fprintf(stderr, ".");
  619. fflush(stderr);
  620. }
  621. }
  622. fprintf(stderr, " done\n");
  623. fprintf(stderr, "%s: model size = %8.2f MB / num tensors = %d\n", __func__, total_size/1024.0/1024.0, model.n_loaded);
  624. if (model.n_loaded == 0) {
  625. fprintf(stderr, "%s: WARN no tensors loaded from model file - assuming empty model for testing\n", __func__);
  626. } else if (model.n_loaded != (int) model.tensors.size()) {
  627. fprintf(stderr, "%s: ERROR not all tensors loaded from model file - expected %zu, got %d\n", __func__, model.tensors.size(), model.n_loaded);
  628. return false;
  629. }
  630. }
  631. fin.close();
  632. }
  633. lctx.t_load_us = ggml_time_us() - t_start_us;
  634. if (progress_callback) {
  635. progress_callback(1.0, progress_callback_user_data);
  636. }
  637. return true;
  638. }
  639. // evaluate the transformer
  640. //
  641. // - lctx: llama context
  642. // - tokens: new batch of tokens to process
  643. // - n_past: the context size so far
  644. // - n_threads: number of threads to use
  645. //
  646. static bool llama_eval_internal(
  647. llama_context & lctx,
  648. const llama_token * tokens,
  649. const int n_tokens,
  650. const int n_past,
  651. const int n_threads) {
  652. const int64_t t_start_us = ggml_time_us();
  653. const int N = n_tokens;
  654. const auto & model = lctx.model;
  655. const auto & hparams = model.hparams;
  656. auto & kv_self = model.kv_self;
  657. LLAMA_ASSERT(!!kv_self.ctx);
  658. const int n_embd = hparams.n_embd;
  659. const int n_layer = hparams.n_layer;
  660. const int n_ctx = hparams.n_ctx;
  661. const int n_head = hparams.n_head;
  662. const int n_vocab = hparams.n_vocab;
  663. const int n_rot = hparams.n_embd/hparams.n_head;
  664. auto & mem_per_token = lctx.mem_per_token;
  665. auto & buf_compute = lctx.buf_compute;
  666. struct ggml_init_params params = {
  667. /*.mem_size =*/ buf_compute.size(),
  668. /*.mem_buffer =*/ buf_compute.data(),
  669. };
  670. struct ggml_context * ctx0 = ggml_init(params);
  671. ggml_cgraph gf = {};
  672. gf.n_threads = n_threads;
  673. struct ggml_tensor * embd = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  674. memcpy(embd->data, tokens, N*ggml_element_size(embd));
  675. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model.tok_embeddings, embd);
  676. for (int il = 0; il < n_layer; ++il) {
  677. struct ggml_tensor * inpSA = inpL;
  678. struct ggml_tensor * cur;
  679. lctx.use_buf(ctx0, 0);
  680. // norm
  681. {
  682. cur = ggml_rms_norm(ctx0, inpL);
  683. // cur = attention_norm*cur
  684. cur = ggml_mul(ctx0,
  685. ggml_repeat(ctx0, model.layers[il].attention_norm, cur),
  686. cur);
  687. }
  688. // self-attention
  689. {
  690. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  691. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  692. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  693. // store key and value to memory
  694. if (N >= 1) {
  695. 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));
  696. struct ggml_tensor * v = ggml_view_1d(ctx0, kv_self.v, N*n_embd, (ggml_element_size(kv_self.v)*n_embd)*(il*n_ctx + n_past));
  697. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Kcur, k));
  698. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Vcur, v));
  699. }
  700. // Q = Qcur.contiguous().view(n_embd/n_head, n_head, N).permute(0, 2, 1, 3)
  701. struct ggml_tensor * Q =
  702. ggml_permute(ctx0,
  703. ggml_rope(ctx0,
  704. ggml_cpy(ctx0,
  705. Qcur,
  706. ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_embd/n_head, n_head, N)),
  707. n_past, n_rot, 0),
  708. 0, 2, 1, 3);
  709. // K = Kmem.view(n_embd/n_head, n_head, n_past + N).permute(0, 2, 1, 3)
  710. struct ggml_tensor * K =
  711. ggml_permute(ctx0,
  712. ggml_rope(ctx0,
  713. ggml_reshape_3d(ctx0,
  714. ggml_view_1d(ctx0, kv_self.k, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(kv_self.k)*n_embd),
  715. n_embd/n_head, n_head, n_past + N),
  716. n_past, n_rot, 1),
  717. 0, 2, 1, 3);
  718. // K * Q
  719. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  720. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  721. struct ggml_tensor * KQ_scaled =
  722. ggml_scale(ctx0,
  723. KQ,
  724. ggml_new_f32(ctx0, 1.0f/sqrt(float(n_embd)/n_head))
  725. );
  726. // KQ_masked = mask_past(KQ_scaled)
  727. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
  728. // KQ = soft_max(KQ_masked)
  729. struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
  730. // V_trans = Vmem.view(n_embd/n_head, n_head, n_past + N).permute(1, 2, 0, 3).contiguous()
  731. struct ggml_tensor * V_trans =
  732. ggml_cpy(ctx0,
  733. ggml_permute(ctx0,
  734. ggml_reshape_3d(ctx0,
  735. ggml_view_1d(ctx0, kv_self.v, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(kv_self.v)*n_embd),
  736. n_embd/n_head, n_head, n_past + N),
  737. 1, 2, 0, 3),
  738. ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_past + N, n_embd/n_head, n_head));
  739. // KQV = transpose(V) * KQ_soft_max
  740. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V_trans, KQ_soft_max);
  741. // KQV_merged = KQV.permute(0, 2, 1, 3)
  742. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  743. // cur = KQV_merged.contiguous().view(n_embd, N)
  744. cur = ggml_cpy(ctx0,
  745. KQV_merged,
  746. ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  747. // projection (no bias)
  748. cur = ggml_mul_mat(ctx0,
  749. model.layers[il].wo,
  750. cur);
  751. }
  752. lctx.use_buf(ctx0, 1);
  753. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  754. // feed-forward network
  755. {
  756. // norm
  757. {
  758. cur = ggml_rms_norm(ctx0, inpFF);
  759. // cur = ffn_norm*cur
  760. cur = ggml_mul(ctx0,
  761. ggml_repeat(ctx0, model.layers[il].ffn_norm, cur),
  762. cur);
  763. }
  764. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  765. model.layers[il].w3,
  766. cur);
  767. cur = ggml_mul_mat(ctx0,
  768. model.layers[il].w1,
  769. cur);
  770. // SILU activation
  771. cur = ggml_silu(ctx0, cur);
  772. cur = ggml_mul(ctx0, cur, tmp);
  773. cur = ggml_mul_mat(ctx0,
  774. model.layers[il].w2,
  775. cur);
  776. }
  777. cur = ggml_add(ctx0, cur, inpFF);
  778. // input for next layer
  779. inpL = cur;
  780. }
  781. lctx.use_buf(ctx0, 0);
  782. // used at the end to optionally extract the embeddings
  783. struct ggml_tensor * embeddings = NULL;
  784. // norm
  785. {
  786. inpL = ggml_rms_norm(ctx0, inpL);
  787. // inpL = norm*inpL
  788. inpL = ggml_mul(ctx0,
  789. ggml_repeat(ctx0, model.norm, inpL),
  790. inpL);
  791. embeddings = inpL;
  792. }
  793. // lm_head
  794. inpL = ggml_mul_mat(ctx0, model.output, inpL);
  795. lctx.use_buf(ctx0, -1);
  796. // logits -> probs
  797. //inpL = ggml_soft_max(ctx0, inpL);
  798. // run the computation
  799. ggml_build_forward_expand(&gf, inpL);
  800. ggml_graph_compute (ctx0, &gf);
  801. //if (n_past%100 == 0) {
  802. // ggml_graph_print (&gf);
  803. // ggml_graph_dump_dot(&gf, NULL, "gpt-2.dot");
  804. //}
  805. //embd_w.resize(n_vocab*N);
  806. //memcpy(embd_w.data(), ggml_get_data(inpL), sizeof(float)*n_vocab*N);
  807. // extract logits
  808. {
  809. auto & logits_out = lctx.logits;
  810. if (lctx.logits_all) {
  811. logits_out.resize(n_vocab * N);
  812. memcpy(logits_out.data(), (float *) ggml_get_data(inpL), sizeof(float)*n_vocab*N);
  813. } else {
  814. // return result for just the last token
  815. logits_out.resize(n_vocab);
  816. memcpy(logits_out.data(), (float *) ggml_get_data(inpL) + (n_vocab*(N-1)), sizeof(float)*n_vocab);
  817. }
  818. }
  819. // extract embeddings
  820. if (lctx.embedding.size()) {
  821. auto & embedding_out = lctx.embedding;
  822. embedding_out.resize(n_embd);
  823. memcpy(embedding_out.data(), (float *) ggml_get_data(embeddings) + (n_embd*(N - 1)), sizeof(float)*n_embd);
  824. }
  825. if (mem_per_token == 0) {
  826. mem_per_token = ggml_used_mem(ctx0)/N;
  827. }
  828. #if 0
  829. printf("\n%s: used_mem = %.3f MB, scratch -- %.3f MB %.3f MB\n", __func__,
  830. ggml_used_mem(ctx0)/1024.0/1024.0,
  831. lctx.get_buf_max_mem(0)/1024.0/1024.0,
  832. lctx.get_buf_max_mem(1)/1024.0/1024.0);
  833. #endif
  834. ggml_free(ctx0);
  835. // measure the performance only for the single-token evals
  836. if (N == 1) {
  837. lctx.t_eval_us += ggml_time_us() - t_start_us;
  838. lctx.n_eval++;
  839. }
  840. return true;
  841. }
  842. //
  843. // tokenizer
  844. //
  845. static size_t utf8_len(char src) {
  846. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  847. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  848. return lookup[highbits];
  849. }
  850. struct llama_sp_symbol {
  851. using index = int;
  852. index prev;
  853. index next;
  854. const char * text;
  855. size_t n;
  856. };
  857. struct llama_sp_bigram {
  858. struct comparator {
  859. bool operator()(llama_sp_bigram & l, llama_sp_bigram & r) {
  860. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  861. }
  862. };
  863. using queue_storage = std::vector<llama_sp_bigram>;
  864. using queue = std::priority_queue<llama_sp_bigram, queue_storage, comparator>;
  865. llama_sp_symbol::index left;
  866. llama_sp_symbol::index right;
  867. float score;
  868. size_t size;
  869. };
  870. // original implementation:
  871. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  872. struct llama_tokenizer {
  873. llama_tokenizer(const llama_vocab & vocab): vocab_(vocab) {}
  874. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  875. // split string into utf8 chars
  876. int index = 0;
  877. size_t offs = 0;
  878. while (offs < text.size()) {
  879. llama_sp_symbol sym;
  880. size_t char_len = std::min(text.size() - offs, utf8_len(text[offs]));
  881. sym.text = text.c_str() + offs;
  882. sym.n = char_len;
  883. offs += char_len;
  884. sym.prev = index - 1;
  885. sym.next = offs == text.size() ? -1 : index + 1;
  886. index++;
  887. symbols_.emplace_back(std::move(sym));
  888. }
  889. // seed the work queue with all possible 2-character tokens.
  890. for (size_t i = 1; i < symbols_.size(); ++i) {
  891. try_add_bigram(i - 1, i);
  892. }
  893. // keep substituting the highest frequency pairs for as long as we can.
  894. while (!work_queue_.empty()) {
  895. auto bigram = work_queue_.top();
  896. work_queue_.pop();
  897. auto & left_sym = symbols_[bigram.left];
  898. auto & right_sym = symbols_[bigram.right];
  899. // if one of the symbols already got merged, skip it.
  900. if (left_sym.n == 0 || right_sym.n == 0 ||
  901. left_sym.n + right_sym.n != bigram.size) {
  902. continue;
  903. }
  904. // merge the right sym into the left one
  905. left_sym.n += right_sym.n;
  906. right_sym.n = 0;
  907. //printf("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  908. // remove the right sym from the chain
  909. left_sym.next = right_sym.next;
  910. if (right_sym.next >= 0) {
  911. symbols_[right_sym.next].prev = bigram.left;
  912. }
  913. // find more substitutions
  914. try_add_bigram(left_sym.prev, bigram.left);
  915. try_add_bigram(bigram.left, left_sym.next);
  916. }
  917. for (int i = 0; i != -1; i = symbols_[i].next) {
  918. auto & symbol = symbols_[i];
  919. auto token = vocab_.token_to_id.find(std::string(symbol.text, symbol.n));
  920. if (token == vocab_.token_to_id.end()) {
  921. // output any symbols that did not form tokens as bytes.
  922. for (int j = 0; j < (int) symbol.n; ++j) {
  923. llama_vocab::id token_id = static_cast<uint8_t>(symbol.text[j]) + 3;
  924. output.push_back(token_id);
  925. }
  926. } else {
  927. output.push_back((*token).second);
  928. }
  929. }
  930. }
  931. private:
  932. void try_add_bigram(int left, int right) {
  933. if (left == -1 || right == -1) {
  934. return;
  935. }
  936. const std::string text = std::string(symbols_[left].text, symbols_[left].n + symbols_[right].n);
  937. auto token = vocab_.token_to_id.find(text);
  938. if (token == vocab_.token_to_id.end()) {
  939. return;
  940. }
  941. if (static_cast<size_t>((*token).second) >= vocab_.id_to_token.size()) {
  942. return;
  943. }
  944. const auto &tok_score = vocab_.id_to_token[(*token).second];
  945. llama_sp_bigram bigram;
  946. bigram.left = left;
  947. bigram.right = right;
  948. bigram.score = tok_score.score;
  949. bigram.size = text.size();
  950. work_queue_.push(bigram);
  951. }
  952. const llama_vocab & vocab_;
  953. std::vector<llama_sp_symbol> symbols_;
  954. llama_sp_bigram::queue work_queue_;
  955. };
  956. static std::vector<llama_vocab::id> llama_tokenize(const llama_vocab & vocab, const std::string & text, bool bos) {
  957. llama_tokenizer tokenizer(vocab);
  958. std::vector<llama_vocab::id> output;
  959. if (text.size() == 0) {
  960. return output;
  961. }
  962. if (bos) {
  963. output.push_back(1);
  964. }
  965. tokenizer.tokenize(text, output);
  966. return output;
  967. }
  968. //
  969. // sampling
  970. //
  971. static void sample_top_k(std::vector<std::pair<double, llama_vocab::id>> & logits_id, int top_k) {
  972. // find the top k tokens
  973. std::partial_sort(
  974. logits_id.begin(),
  975. logits_id.begin() + top_k, logits_id.end(),
  976. [](const std::pair<double, llama_vocab::id> & a, const std::pair<double, llama_vocab::id> & b) {
  977. return a.first > b.first;
  978. });
  979. logits_id.resize(top_k);
  980. }
  981. static llama_vocab::id llama_sample_top_p_top_k(
  982. llama_context & lctx,
  983. const std::vector<llama_vocab::id> & last_n_tokens,
  984. int top_k,
  985. double top_p,
  986. double temp,
  987. double repeat_penalty) {
  988. auto & rng = lctx.rng;
  989. const auto & vocab = lctx.vocab;
  990. const auto & logits = lctx.logits;
  991. int n_logits = vocab.id_to_token.size();
  992. std::vector<std::pair<double, llama_vocab::id>> logits_id;
  993. logits_id.reserve(n_logits);
  994. {
  995. const double scale = 1.0/temp;
  996. for (int i = 0; i < n_logits; ++i) {
  997. // repetition penalty from ctrl paper (https://arxiv.org/abs/1909.05858)
  998. // credit https://github.com/facebookresearch/llama/compare/main...shawwn:llama:main
  999. if (std::find(last_n_tokens.begin(), last_n_tokens.end(), i) != last_n_tokens.end()) {
  1000. // if score < 0 then repetition penalty has to multiplied to reduce the previous token probability
  1001. if (logits[i] < 0.0) {
  1002. logits_id.push_back(std::make_pair(logits[i]*scale*repeat_penalty, i));
  1003. } else {
  1004. logits_id.push_back(std::make_pair(logits[i]*scale/repeat_penalty, i));
  1005. }
  1006. } else {
  1007. logits_id.push_back(std::make_pair(logits[i]*scale, i));
  1008. }
  1009. }
  1010. }
  1011. sample_top_k(logits_id, top_k);
  1012. double maxl = -std::numeric_limits<double>::infinity();
  1013. for (const auto & kv : logits_id) {
  1014. maxl = std::max(maxl, kv.first);
  1015. }
  1016. // compute probs for the top k tokens
  1017. std::vector<double> probs;
  1018. probs.reserve(logits_id.size());
  1019. double sum = 0.0;
  1020. for (const auto & kv : logits_id) {
  1021. double p = exp(kv.first - maxl);
  1022. probs.push_back(p);
  1023. sum += p;
  1024. }
  1025. // normalize the probs
  1026. for (auto & p : probs) {
  1027. p /= sum;
  1028. }
  1029. if (top_p < 1.0f) {
  1030. double cumsum = 0.0f;
  1031. for (int i = 0; i < (int) probs.size(); i++) {
  1032. cumsum += probs[i];
  1033. if (cumsum >= top_p) {
  1034. probs.resize(i + 1);
  1035. logits_id.resize(i + 1);
  1036. break;
  1037. }
  1038. }
  1039. cumsum = 1.0/cumsum;
  1040. for (int i = 0; i < (int) probs.size(); i++) {
  1041. probs[i] *= cumsum;
  1042. }
  1043. }
  1044. //printf("\n");
  1045. //for (int i = 0; i < (int) 10; i++) {
  1046. // printf("%d: '%s' %f\n", i, vocab.id_to_token.at(logits_id[i].second).c_str(), probs[i]);
  1047. //}
  1048. //printf("\n\n");
  1049. //exit(0);
  1050. std::discrete_distribution<> dist(probs.begin(), probs.end());
  1051. int idx = dist(rng);
  1052. return logits_id[idx].second;
  1053. }
  1054. //
  1055. // quantization
  1056. //
  1057. // TODO: reuse code from the llama_model_load() somehow
  1058. bool llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, int itype, int qk) {
  1059. ggml_type type = GGML_TYPE_Q4_1;
  1060. switch (itype) {
  1061. case 2: type = GGML_TYPE_Q4_0; break;
  1062. case 3: type = GGML_TYPE_Q4_1; break;
  1063. default: fprintf(stderr, "%s: invalid quantization type %d\n", __func__, itype); return 1;
  1064. };
  1065. if (type != GGML_TYPE_Q4_0 && type != GGML_TYPE_Q4_1) {
  1066. fprintf(stderr, "%s: invalid quantization type %d\n", __func__, type);
  1067. return false;
  1068. }
  1069. llama_vocab vocab;
  1070. printf("%s: loading model from '%s'\n", __func__, fname_inp.c_str());
  1071. auto finp = std::ifstream(fname_inp, std::ios::binary);
  1072. if (!finp) {
  1073. fprintf(stderr, "%s: failed to open '%s' for reading\n", __func__, fname_inp.c_str());
  1074. return false;
  1075. }
  1076. auto fout = std::ofstream(fname_out, std::ios::binary);
  1077. if (!fout) {
  1078. fprintf(stderr, "%s: failed to open '%s' for writing\n", __func__, fname_out.c_str());
  1079. return false;
  1080. }
  1081. // verify magic
  1082. {
  1083. uint32_t magic;
  1084. finp.read((char *) &magic, sizeof(magic));
  1085. if (magic == LLAMA_FILE_MAGIC_UNVERSIONED) {
  1086. fprintf(stderr, "%s: invalid model file '%s' (too old, regenerate your model files!)\n",
  1087. __func__, fname_inp.c_str());
  1088. return false;
  1089. }
  1090. if (magic != LLAMA_FILE_MAGIC) {
  1091. fprintf(stderr, "%s: invalid model file '%s' (bad magic)\n", __func__, fname_inp.c_str());
  1092. return false;
  1093. }
  1094. fout.write((char *) &magic, sizeof(magic));
  1095. uint32_t format_version;
  1096. finp.read((char *) &format_version, sizeof(format_version));
  1097. if (format_version != LLAMA_FILE_VERSION) {
  1098. fprintf(stderr, "%s: invalid model file '%s' (unsupported format version %" PRIu32 ", expected %d)\n",
  1099. __func__, fname_inp.c_str(), format_version, LLAMA_FILE_VERSION);
  1100. return false;
  1101. }
  1102. fout.write((char *) &format_version, sizeof(format_version));
  1103. }
  1104. llama_hparams hparams;
  1105. // load hparams
  1106. {
  1107. finp.read((char *) &hparams.n_vocab, sizeof(hparams.n_vocab));
  1108. //finp.read((char *) &hparams.n_ctx, sizeof(hparams.n_ctx));
  1109. finp.read((char *) &hparams.n_embd, sizeof(hparams.n_embd));
  1110. finp.read((char *) &hparams.n_mult, sizeof(hparams.n_mult));
  1111. finp.read((char *) &hparams.n_head, sizeof(hparams.n_head));
  1112. finp.read((char *) &hparams.n_layer, sizeof(hparams.n_layer));
  1113. finp.read((char *) &hparams.n_rot, sizeof(hparams.n_rot));
  1114. finp.read((char *) &hparams.f16, sizeof(hparams.f16));
  1115. printf("%s: n_vocab = %d\n", __func__, hparams.n_vocab);
  1116. printf("%s: n_ctx = %d\n", __func__, hparams.n_ctx);
  1117. printf("%s: n_embd = %d\n", __func__, hparams.n_embd);
  1118. printf("%s: n_mult = %d\n", __func__, hparams.n_mult);
  1119. printf("%s: n_head = %d\n", __func__, hparams.n_head);
  1120. printf("%s: n_layer = %d\n", __func__, hparams.n_layer);
  1121. printf("%s: f16 = %d\n", __func__, hparams.f16);
  1122. fout.write((char *) &hparams.n_vocab, sizeof(hparams.n_vocab));
  1123. //fout.write((char *) &hparams.n_ctx, sizeof(hparams.n_ctx));
  1124. fout.write((char *) &hparams.n_embd, sizeof(hparams.n_embd));
  1125. fout.write((char *) &hparams.n_mult, sizeof(hparams.n_mult));
  1126. fout.write((char *) &hparams.n_head, sizeof(hparams.n_head));
  1127. fout.write((char *) &hparams.n_layer, sizeof(hparams.n_layer));
  1128. fout.write((char *) &hparams.n_rot, sizeof(hparams.n_rot));
  1129. fout.write((char *) &itype, sizeof(hparams.f16));
  1130. }
  1131. // load vocab
  1132. {
  1133. const int32_t n_vocab = hparams.n_vocab;
  1134. if (n_vocab != hparams.n_vocab) {
  1135. fprintf(stderr, "%s: invalid model file '%s' (bad vocab size %d != %d)\n",
  1136. __func__, fname_inp.c_str(), n_vocab, hparams.n_vocab);
  1137. return false;
  1138. }
  1139. std::string word;
  1140. vocab.id_to_token.resize(n_vocab);
  1141. for (int i = 0; i < n_vocab; i++) {
  1142. uint32_t len;
  1143. finp.read ((char *) &len, sizeof(len));
  1144. fout.write((char *) &len, sizeof(len));
  1145. word.resize(len);
  1146. finp.read ((char *) word.data(), len);
  1147. fout.write((char *) word.data(), len);
  1148. float score;
  1149. finp.read ((char *) &score, sizeof(score));
  1150. fout.write((char *) &score, sizeof(score));
  1151. vocab.token_to_id[word] = i;
  1152. auto &tok_score = vocab.id_to_token[i];
  1153. tok_score.tok = word;
  1154. tok_score.score = score;
  1155. }
  1156. }
  1157. // load weights
  1158. {
  1159. size_t total_size_org = 0;
  1160. size_t total_size_new = 0;
  1161. std::vector<float> work;
  1162. std::vector<uint8_t> data_u8;
  1163. std::vector<ggml_fp16_t> data_f16;
  1164. std::vector<float> data_f32;
  1165. std::vector<int64_t> hist_all(1 << 4, 0);
  1166. while (true) {
  1167. int32_t n_dims;
  1168. int32_t length;
  1169. int32_t ftype;
  1170. finp.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  1171. finp.read(reinterpret_cast<char *>(&length), sizeof(length));
  1172. finp.read(reinterpret_cast<char *>(&ftype), sizeof(ftype));
  1173. if (finp.eof()) {
  1174. break;
  1175. }
  1176. int32_t nelements = 1;
  1177. int32_t ne[2] = { 1, 1 };
  1178. for (int i = 0; i < n_dims; ++i) {
  1179. finp.read (reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  1180. nelements *= ne[i];
  1181. }
  1182. std::string name(length, 0);
  1183. finp.read (&name[0], length);
  1184. {
  1185. static const char * ftype_str[] = { "f32", "f16", "q4_0", "q4_1", };
  1186. printf("%48s - [%5d, %5d], type = %6s ", name.data(), ne[0], ne[1], ftype_str[ftype]);
  1187. }
  1188. // regexes of tensor names to be quantized
  1189. const std::vector<std::string> k_names = {
  1190. ".*weight",
  1191. };
  1192. bool quantize = false;
  1193. for (const auto & s : k_names) {
  1194. if (std::regex_match(name, std::regex(s))) {
  1195. quantize = true;
  1196. break;
  1197. }
  1198. }
  1199. // quantize only 2D tensors
  1200. quantize &= (n_dims == 2);
  1201. if (quantize) {
  1202. if (ftype != 0 && ftype != 1) {
  1203. fprintf(stderr, "%s: unsupported ftype %d for integer quantization\n", __func__, ftype);
  1204. return false;
  1205. }
  1206. if (ftype == 1) {
  1207. data_f16.resize(nelements);
  1208. finp.read(reinterpret_cast<char *>(data_f16.data()), nelements * sizeof(ggml_fp16_t));
  1209. data_f32.resize(nelements);
  1210. for (int i = 0; i < nelements; ++i) {
  1211. data_f32[i] = ggml_fp16_to_fp32(data_f16[i]);
  1212. }
  1213. } else {
  1214. data_f32.resize(nelements);
  1215. finp.read(reinterpret_cast<char *>(data_f32.data()), nelements * sizeof(float));
  1216. }
  1217. ftype = itype;
  1218. } else {
  1219. const int bpe = (ftype == 0) ? sizeof(float) : sizeof(uint16_t);
  1220. data_u8.resize(nelements*bpe);
  1221. finp.read(reinterpret_cast<char *>(data_u8.data()), nelements * bpe);
  1222. }
  1223. fout.write(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  1224. fout.write(reinterpret_cast<char *>(&length), sizeof(length));
  1225. fout.write(reinterpret_cast<char *>(&ftype), sizeof(ftype));
  1226. for (int i = 0; i < n_dims; ++i) {
  1227. fout.write(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  1228. }
  1229. fout.write(&name[0], length);
  1230. if (quantize) {
  1231. printf("quantizing .. ");
  1232. work.resize(nelements); // for quantization
  1233. size_t cur_size = 0;
  1234. std::vector<int64_t> hist_cur(1 << 4, 0);
  1235. switch (type) {
  1236. case GGML_TYPE_Q4_0:
  1237. {
  1238. cur_size = ggml_quantize_q4_0(data_f32.data(), work.data(), nelements, ne[0], qk, hist_cur.data());
  1239. } break;
  1240. case GGML_TYPE_Q4_1:
  1241. {
  1242. cur_size = ggml_quantize_q4_1(data_f32.data(), work.data(), nelements, ne[0], qk, hist_cur.data());
  1243. } break;
  1244. default:
  1245. {
  1246. fprintf(stderr, "%s: unsupported quantization type %d\n", __func__, type);
  1247. return false;
  1248. }
  1249. }
  1250. fout.write(reinterpret_cast<char *>(work.data()), cur_size);
  1251. total_size_new += cur_size;
  1252. printf("size = %8.2f MB -> %8.2f MB | hist: ", nelements * sizeof(float)/1024.0/1024.0, cur_size/1024.0/1024.0);
  1253. for (int i = 0; i < (int) hist_cur.size(); ++i) {
  1254. hist_all[i] += hist_cur[i];
  1255. }
  1256. for (int i = 0; i < (int) hist_cur.size(); ++i) {
  1257. printf("%5.3f ", hist_cur[i] / (float)nelements);
  1258. }
  1259. printf("\n");
  1260. } else {
  1261. printf("size = %8.3f MB\n", data_u8.size()/1024.0/1024.0);
  1262. fout.write(reinterpret_cast<char *>(data_u8.data()), data_u8.size());
  1263. total_size_new += data_u8.size();
  1264. }
  1265. total_size_org += nelements * sizeof(float);
  1266. }
  1267. printf("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  1268. printf("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  1269. {
  1270. int64_t sum_all = 0;
  1271. for (int i = 0; i < (int) hist_all.size(); ++i) {
  1272. sum_all += hist_all[i];
  1273. }
  1274. printf("%s: hist: ", __func__);
  1275. for (int i = 0; i < (int) hist_all.size(); ++i) {
  1276. printf("%5.3f ", hist_all[i] / (float)sum_all);
  1277. }
  1278. printf("\n");
  1279. }
  1280. }
  1281. finp.close();
  1282. fout.close();
  1283. return true;
  1284. }
  1285. //
  1286. // interface implementation
  1287. //
  1288. struct llama_context * llama_init_from_file(
  1289. const char * path_model,
  1290. struct llama_context_params params) {
  1291. ggml_time_init();
  1292. llama_context * ctx = new llama_context;
  1293. if (params.seed <= 0) {
  1294. params.seed = time(NULL);
  1295. }
  1296. ctx->rng = std::mt19937(params.seed);
  1297. ctx->logits_all = params.logits_all;
  1298. ggml_type memory_type = params.f16_kv ? GGML_TYPE_F16 : GGML_TYPE_F32;
  1299. if (!llama_model_load(path_model, *ctx, params.n_ctx, params.n_parts, memory_type,
  1300. params.vocab_only, params.progress_callback,
  1301. params.progress_callback_user_data)) {
  1302. fprintf(stderr, "%s: failed to load model\n", __func__);
  1303. llama_free(ctx);
  1304. return nullptr;
  1305. }
  1306. if (params.use_mlock) {
  1307. char *err;
  1308. if (!ggml_mlock(ctx->model.ctx, &err)) {
  1309. fprintf(stderr, "%s\n", err);
  1310. free(err);
  1311. llama_free(ctx);
  1312. return nullptr;
  1313. }
  1314. }
  1315. // reserve memory for context buffers
  1316. {
  1317. if (!kv_cache_init(ctx->model.hparams, ctx->model.kv_self, memory_type, ctx->model.hparams.n_ctx)) {
  1318. fprintf(stderr, "%s: kv_cache_init() failed for self-attention cache\n", __func__);
  1319. llama_free(ctx);
  1320. return nullptr;
  1321. }
  1322. {
  1323. const size_t memory_size = ggml_nbytes(ctx->model.kv_self.k) + ggml_nbytes(ctx->model.kv_self.v);
  1324. fprintf(stderr, "%s: kv self size = %7.2f MB\n", __func__, memory_size / 1024.0 / 1024.0);
  1325. }
  1326. const auto & hparams = ctx->model.hparams;
  1327. if (params.logits_all) {
  1328. ctx->logits.reserve(hparams.n_ctx*hparams.n_vocab);
  1329. } else {
  1330. ctx->logits.reserve(hparams.n_ctx);
  1331. }
  1332. if (params.embedding){
  1333. ctx->embedding.reserve(hparams.n_embd);
  1334. }
  1335. ctx->buf_compute.resize(MEM_REQ_EVAL.at(ctx->model.type));
  1336. ctx->buf_scratch[0].resize(MEM_REQ_SCRATCH0.at(ctx->model.type));
  1337. ctx->buf_scratch[1].resize(MEM_REQ_SCRATCH1.at(ctx->model.type));
  1338. }
  1339. return ctx;
  1340. }
  1341. void llama_free(struct llama_context * ctx) {
  1342. kv_cache_free(ctx->model.kv_self);
  1343. if (ctx->model.ctx) {
  1344. ggml_free(ctx->model.ctx);
  1345. }
  1346. delete ctx;
  1347. }
  1348. int llama_model_quantize(
  1349. const char * fname_inp,
  1350. const char * fname_out,
  1351. int itype,
  1352. int qk) {
  1353. if (!llama_model_quantize_internal(fname_inp, fname_out, itype, qk)) {
  1354. fprintf(stderr, "%s: failed to quantize\n", __func__);
  1355. return 1;
  1356. }
  1357. return 0;
  1358. }
  1359. int llama_eval(
  1360. struct llama_context * ctx,
  1361. const llama_token * tokens,
  1362. int n_tokens,
  1363. int n_past,
  1364. int n_threads) {
  1365. if (!llama_eval_internal(*ctx, tokens, n_tokens, n_past, n_threads)) {
  1366. fprintf(stderr, "%s: failed to eval\n", __func__);
  1367. return 1;
  1368. }
  1369. return 0;
  1370. }
  1371. int llama_tokenize(
  1372. struct llama_context * ctx,
  1373. const char * text,
  1374. llama_token * tokens,
  1375. int n_max_tokens,
  1376. bool add_bos) {
  1377. auto res = llama_tokenize(ctx->vocab, text, add_bos);
  1378. if (n_max_tokens < (int) res.size()) {
  1379. fprintf(stderr, "%s: too many tokens\n", __func__);
  1380. return -((int) res.size());
  1381. }
  1382. for (size_t i = 0; i < res.size(); i++) {
  1383. tokens[i] = res[i];
  1384. }
  1385. return res.size();
  1386. }
  1387. int llama_n_vocab(struct llama_context * ctx) {
  1388. return ctx->vocab.id_to_token.size();
  1389. }
  1390. int llama_n_ctx(struct llama_context * ctx) {
  1391. return ctx->model.hparams.n_ctx;
  1392. }
  1393. float * llama_get_logits(struct llama_context * ctx) {
  1394. return ctx->logits.data();
  1395. }
  1396. float * llama_get_embeddings(struct llama_context * ctx) {
  1397. return ctx->embedding.data();
  1398. }
  1399. const char * llama_token_to_str(struct llama_context * ctx, llama_token token) {
  1400. if (token >= llama_n_vocab(ctx)) {
  1401. return nullptr;
  1402. }
  1403. return ctx->vocab.id_to_token[token].tok.c_str();
  1404. }
  1405. llama_token llama_token_bos() {
  1406. return 1;
  1407. }
  1408. llama_token llama_token_eos() {
  1409. return 2;
  1410. }
  1411. llama_token llama_sample_top_p_top_k(
  1412. llama_context * ctx,
  1413. const llama_token * last_n_tokens_data,
  1414. int last_n_tokens_size,
  1415. int top_k,
  1416. double top_p,
  1417. double temp,
  1418. double repeat_penalty) {
  1419. const int64_t t_start_sample_us = ggml_time_us();
  1420. llama_token result = 0;
  1421. // TODO: avoid this ...
  1422. const auto last_n_tokens = std::vector<llama_token>(last_n_tokens_data, last_n_tokens_data + last_n_tokens_size);
  1423. result = llama_sample_top_p_top_k(
  1424. *ctx,
  1425. last_n_tokens,
  1426. top_k,
  1427. top_p,
  1428. temp,
  1429. repeat_penalty);
  1430. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1431. ctx->n_sample++;
  1432. return result;
  1433. }
  1434. void llama_print_timings(struct llama_context * ctx) {
  1435. const int64_t t_end_us = ggml_time_us();
  1436. const int32_t n_sample = std::max(1, ctx->n_sample);
  1437. const int32_t n_eval = std::max(1, ctx->n_eval);
  1438. fprintf(stderr, "\n");
  1439. fprintf(stderr, "%s: load time = %8.2f ms\n", __func__, ctx->t_load_us / 1000.0f);
  1440. fprintf(stderr, "%s: sample time = %8.2f ms / %5d runs (%8.2f ms per run)\n", __func__, 1e-3f * ctx->t_sample_us, n_sample, 1e-3f * ctx->t_sample_us / n_sample);
  1441. fprintf(stderr, "%s: eval time = %8.2f ms / %5d runs (%8.2f ms per run)\n", __func__, 1e-3f * ctx->t_eval_us, n_eval, 1e-3f * ctx->t_eval_us / n_eval);
  1442. fprintf(stderr, "%s: total time = %8.2f ms\n", __func__, (t_end_us - ctx->t_start_us)/1000.0f);
  1443. }
  1444. void llama_reset_timings(struct llama_context * ctx) {
  1445. ctx->t_start_us = ggml_time_us();
  1446. ctx->t_sample_us = ctx->n_sample = 0;
  1447. ctx->t_eval_us = ctx->n_eval = 0;
  1448. }
  1449. const char * llama_print_system_info(void) {
  1450. static std::string s;
  1451. s = "";
  1452. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  1453. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  1454. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  1455. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  1456. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  1457. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  1458. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  1459. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  1460. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  1461. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  1462. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  1463. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  1464. return s.c_str();
  1465. }