llama.cpp 61 KB

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