llama.cpp 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856
  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. ggml_cgraph gf = {};
  674. gf.n_threads = n_threads;
  675. struct ggml_tensor * embd = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  676. memcpy(embd->data, tokens, N*ggml_element_size(embd));
  677. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model.tok_embeddings, embd);
  678. for (int il = 0; il < n_layer; ++il) {
  679. struct ggml_tensor * inpSA = inpL;
  680. struct ggml_tensor * cur;
  681. lctx.use_buf(ctx0, 0);
  682. // norm
  683. {
  684. cur = ggml_rms_norm(ctx0, inpL);
  685. // cur = attention_norm*cur
  686. cur = ggml_mul(ctx0,
  687. ggml_repeat(ctx0, model.layers[il].attention_norm, cur),
  688. cur);
  689. }
  690. // self-attention
  691. {
  692. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  693. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  694. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  695. // store key and value to memory
  696. if (N >= 1) {
  697. 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));
  698. 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));
  699. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Kcur, k));
  700. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Vcur, v));
  701. }
  702. // Q = Qcur.contiguous().view(n_embd/n_head, n_head, N).permute(0, 2, 1, 3)
  703. struct ggml_tensor * Q =
  704. ggml_permute(ctx0,
  705. ggml_rope(ctx0,
  706. ggml_cpy(ctx0,
  707. Qcur,
  708. ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_embd/n_head, n_head, N)),
  709. n_past, n_rot, 0),
  710. 0, 2, 1, 3);
  711. // K = Kmem.view(n_embd/n_head, n_head, n_past + N).permute(0, 2, 1, 3)
  712. struct ggml_tensor * K =
  713. ggml_permute(ctx0,
  714. ggml_rope(ctx0,
  715. ggml_reshape_3d(ctx0,
  716. ggml_view_1d(ctx0, kv_self.k, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(kv_self.k)*n_embd),
  717. n_embd/n_head, n_head, n_past + N),
  718. n_past, n_rot, 1),
  719. 0, 2, 1, 3);
  720. // K * Q
  721. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  722. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  723. struct ggml_tensor * KQ_scaled =
  724. ggml_scale(ctx0,
  725. KQ,
  726. ggml_new_f32(ctx0, 1.0f/sqrt(float(n_embd)/n_head)));
  727. // KQ_masked = mask_past(KQ_scaled)
  728. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
  729. // KQ = soft_max(KQ_masked)
  730. struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
  731. // V_trans = Vmem.view(n_embd/n_head, n_head, n_past + N).permute(1, 2, 0, 3).contiguous()
  732. struct ggml_tensor * V_trans =
  733. ggml_cpy(ctx0,
  734. ggml_permute(ctx0,
  735. ggml_reshape_3d(ctx0,
  736. ggml_view_1d(ctx0, kv_self.v, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(kv_self.v)*n_embd),
  737. n_embd/n_head, n_head, n_past + N),
  738. 1, 2, 0, 3),
  739. ggml_new_tensor_3d(ctx0, kv_self.v->type, n_past + N, n_embd/n_head, n_head));
  740. // KQV = transpose(V) * KQ_soft_max
  741. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V_trans, KQ_soft_max);
  742. // KQV_merged = KQV.permute(0, 2, 1, 3)
  743. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  744. // cur = KQV_merged.contiguous().view(n_embd, N)
  745. cur = ggml_cpy(ctx0,
  746. KQV_merged,
  747. ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  748. // projection (no bias)
  749. cur = ggml_mul_mat(ctx0,
  750. model.layers[il].wo,
  751. cur);
  752. }
  753. lctx.use_buf(ctx0, 1);
  754. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  755. // feed-forward network
  756. {
  757. // norm
  758. {
  759. cur = ggml_rms_norm(ctx0, inpFF);
  760. // cur = ffn_norm*cur
  761. cur = ggml_mul(ctx0,
  762. ggml_repeat(ctx0, model.layers[il].ffn_norm, cur),
  763. cur);
  764. }
  765. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  766. model.layers[il].w3,
  767. cur);
  768. cur = ggml_mul_mat(ctx0,
  769. model.layers[il].w1,
  770. cur);
  771. // SILU activation
  772. cur = ggml_silu(ctx0, cur);
  773. cur = ggml_mul(ctx0, cur, tmp);
  774. cur = ggml_mul_mat(ctx0,
  775. model.layers[il].w2,
  776. cur);
  777. }
  778. cur = ggml_add(ctx0, cur, inpFF);
  779. // input for next layer
  780. inpL = cur;
  781. }
  782. lctx.use_buf(ctx0, 0);
  783. // used at the end to optionally extract the embeddings
  784. struct ggml_tensor * embeddings = NULL;
  785. // norm
  786. {
  787. inpL = ggml_rms_norm(ctx0, inpL);
  788. // inpL = norm*inpL
  789. inpL = ggml_mul(ctx0,
  790. ggml_repeat(ctx0, model.norm, inpL),
  791. inpL);
  792. embeddings = inpL;
  793. }
  794. // lm_head
  795. inpL = ggml_mul_mat(ctx0, model.output, inpL);
  796. lctx.use_buf(ctx0, -1);
  797. // logits -> probs
  798. //inpL = ggml_soft_max(ctx0, inpL);
  799. // run the computation
  800. ggml_build_forward_expand(&gf, inpL);
  801. ggml_graph_compute (ctx0, &gf);
  802. //if (n_past%100 == 0) {
  803. // ggml_graph_print (&gf);
  804. // ggml_graph_dump_dot(&gf, NULL, "gpt-2.dot");
  805. //}
  806. //embd_w.resize(n_vocab*N);
  807. //memcpy(embd_w.data(), ggml_get_data(inpL), sizeof(float)*n_vocab*N);
  808. // extract logits
  809. {
  810. auto & logits_out = lctx.logits;
  811. if (lctx.logits_all) {
  812. logits_out.resize(n_vocab * N);
  813. memcpy(logits_out.data(), (float *) ggml_get_data(inpL), sizeof(float)*n_vocab*N);
  814. } else {
  815. // return result for just the last token
  816. logits_out.resize(n_vocab);
  817. memcpy(logits_out.data(), (float *) ggml_get_data(inpL) + (n_vocab*(N-1)), sizeof(float)*n_vocab);
  818. }
  819. }
  820. // extract embeddings
  821. if (lctx.embedding.size()) {
  822. auto & embedding_out = lctx.embedding;
  823. embedding_out.resize(n_embd);
  824. memcpy(embedding_out.data(), (float *) ggml_get_data(embeddings) + (n_embd*(N - 1)), sizeof(float)*n_embd);
  825. }
  826. if (mem_per_token == 0) {
  827. mem_per_token = ggml_used_mem(ctx0)/N;
  828. }
  829. #if 0
  830. printf("\n%s: used_mem = %.3f MB, scratch -- %.3f MB %.3f MB\n", __func__,
  831. ggml_used_mem(ctx0)/1024.0/1024.0,
  832. lctx.get_buf_max_mem(0)/1024.0/1024.0,
  833. lctx.get_buf_max_mem(1)/1024.0/1024.0);
  834. #endif
  835. ggml_free(ctx0);
  836. // measure the performance only for the single-token evals
  837. if (N == 1) {
  838. lctx.t_eval_us += ggml_time_us() - t_start_us;
  839. lctx.n_eval++;
  840. }
  841. else if (N > 1) {
  842. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  843. lctx.n_p_eval += N;
  844. }
  845. return true;
  846. }
  847. //
  848. // tokenizer
  849. //
  850. static size_t utf8_len(char src) {
  851. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  852. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  853. return lookup[highbits];
  854. }
  855. struct llama_sp_symbol {
  856. using index = int;
  857. index prev;
  858. index next;
  859. const char * text;
  860. size_t n;
  861. };
  862. struct llama_sp_bigram {
  863. struct comparator {
  864. bool operator()(llama_sp_bigram & l, llama_sp_bigram & r) {
  865. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  866. }
  867. };
  868. using queue_storage = std::vector<llama_sp_bigram>;
  869. using queue = std::priority_queue<llama_sp_bigram, queue_storage, comparator>;
  870. llama_sp_symbol::index left;
  871. llama_sp_symbol::index right;
  872. float score;
  873. size_t size;
  874. };
  875. // original implementation:
  876. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  877. struct llama_tokenizer {
  878. llama_tokenizer(const llama_vocab & vocab): vocab_(vocab) {}
  879. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  880. // split string into utf8 chars
  881. int index = 0;
  882. size_t offs = 0;
  883. while (offs < text.size()) {
  884. llama_sp_symbol sym;
  885. size_t char_len = std::min(text.size() - offs, utf8_len(text[offs]));
  886. sym.text = text.c_str() + offs;
  887. sym.n = char_len;
  888. offs += char_len;
  889. sym.prev = index - 1;
  890. sym.next = offs == text.size() ? -1 : index + 1;
  891. index++;
  892. symbols_.emplace_back(std::move(sym));
  893. }
  894. // seed the work queue with all possible 2-character tokens.
  895. for (size_t i = 1; i < symbols_.size(); ++i) {
  896. try_add_bigram(i - 1, i);
  897. }
  898. // keep substituting the highest frequency pairs for as long as we can.
  899. while (!work_queue_.empty()) {
  900. auto bigram = work_queue_.top();
  901. work_queue_.pop();
  902. auto & left_sym = symbols_[bigram.left];
  903. auto & right_sym = symbols_[bigram.right];
  904. // if one of the symbols already got merged, skip it.
  905. if (left_sym.n == 0 || right_sym.n == 0 ||
  906. left_sym.n + right_sym.n != bigram.size) {
  907. continue;
  908. }
  909. // merge the right sym into the left one
  910. left_sym.n += right_sym.n;
  911. right_sym.n = 0;
  912. //printf("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  913. // remove the right sym from the chain
  914. left_sym.next = right_sym.next;
  915. if (right_sym.next >= 0) {
  916. symbols_[right_sym.next].prev = bigram.left;
  917. }
  918. // find more substitutions
  919. try_add_bigram(left_sym.prev, bigram.left);
  920. try_add_bigram(bigram.left, left_sym.next);
  921. }
  922. for (int i = 0; i != -1; i = symbols_[i].next) {
  923. auto & symbol = symbols_[i];
  924. auto token = vocab_.token_to_id.find(std::string(symbol.text, symbol.n));
  925. if (token == vocab_.token_to_id.end()) {
  926. // output any symbols that did not form tokens as bytes.
  927. for (int j = 0; j < (int) symbol.n; ++j) {
  928. llama_vocab::id token_id = static_cast<uint8_t>(symbol.text[j]) + 3;
  929. output.push_back(token_id);
  930. }
  931. } else {
  932. output.push_back((*token).second);
  933. }
  934. }
  935. }
  936. private:
  937. void try_add_bigram(int left, int right) {
  938. if (left == -1 || right == -1) {
  939. return;
  940. }
  941. const std::string text = std::string(symbols_[left].text, symbols_[left].n + symbols_[right].n);
  942. auto token = vocab_.token_to_id.find(text);
  943. if (token == vocab_.token_to_id.end()) {
  944. return;
  945. }
  946. if (static_cast<size_t>((*token).second) >= vocab_.id_to_token.size()) {
  947. return;
  948. }
  949. const auto &tok_score = vocab_.id_to_token[(*token).second];
  950. llama_sp_bigram bigram;
  951. bigram.left = left;
  952. bigram.right = right;
  953. bigram.score = tok_score.score;
  954. bigram.size = text.size();
  955. work_queue_.push(bigram);
  956. }
  957. const llama_vocab & vocab_;
  958. std::vector<llama_sp_symbol> symbols_;
  959. llama_sp_bigram::queue work_queue_;
  960. };
  961. static std::vector<llama_vocab::id> llama_tokenize(const llama_vocab & vocab, const std::string & text, bool bos) {
  962. llama_tokenizer tokenizer(vocab);
  963. std::vector<llama_vocab::id> output;
  964. if (text.size() == 0) {
  965. return output;
  966. }
  967. if (bos) {
  968. output.push_back(1);
  969. }
  970. tokenizer.tokenize(text, output);
  971. return output;
  972. }
  973. //
  974. // sampling
  975. //
  976. static void sample_top_k(std::vector<std::pair<double, llama_vocab::id>> & logits_id, int top_k) {
  977. // find the top k tokens
  978. std::partial_sort(
  979. logits_id.begin(),
  980. logits_id.begin() + top_k, logits_id.end(),
  981. [](const std::pair<double, llama_vocab::id> & a, const std::pair<double, llama_vocab::id> & b) {
  982. return a.first > b.first;
  983. });
  984. logits_id.resize(top_k);
  985. }
  986. static llama_vocab::id llama_sample_top_p_top_k(
  987. llama_context & lctx,
  988. const std::vector<llama_vocab::id> & last_n_tokens,
  989. int top_k,
  990. double top_p,
  991. double temp,
  992. double repeat_penalty) {
  993. auto & rng = lctx.rng;
  994. const auto & vocab = lctx.vocab;
  995. const auto & logits = lctx.logits;
  996. int n_logits = vocab.id_to_token.size();
  997. std::vector<std::pair<double, llama_vocab::id>> logits_id;
  998. logits_id.reserve(n_logits);
  999. {
  1000. const double scale = 1.0/temp;
  1001. for (int i = 0; i < n_logits; ++i) {
  1002. // repetition penalty from ctrl paper (https://arxiv.org/abs/1909.05858)
  1003. // credit https://github.com/facebookresearch/llama/compare/main...shawwn:llama:main
  1004. if (std::find(last_n_tokens.begin(), last_n_tokens.end(), i) != last_n_tokens.end()) {
  1005. // if score < 0 then repetition penalty has to multiplied to reduce the previous token probability
  1006. if (logits[i] < 0.0) {
  1007. logits_id.push_back(std::make_pair(logits[i]*scale*repeat_penalty, i));
  1008. } else {
  1009. logits_id.push_back(std::make_pair(logits[i]*scale/repeat_penalty, i));
  1010. }
  1011. } else {
  1012. logits_id.push_back(std::make_pair(logits[i]*scale, i));
  1013. }
  1014. }
  1015. }
  1016. sample_top_k(logits_id, top_k);
  1017. double maxl = -std::numeric_limits<double>::infinity();
  1018. for (const auto & kv : logits_id) {
  1019. maxl = std::max(maxl, kv.first);
  1020. }
  1021. // compute probs for the top k tokens
  1022. std::vector<double> probs;
  1023. probs.reserve(logits_id.size());
  1024. double sum = 0.0;
  1025. for (const auto & kv : logits_id) {
  1026. double p = exp(kv.first - maxl);
  1027. probs.push_back(p);
  1028. sum += p;
  1029. }
  1030. // normalize the probs
  1031. for (auto & p : probs) {
  1032. p /= sum;
  1033. }
  1034. if (top_p < 1.0f) {
  1035. double cumsum = 0.0f;
  1036. for (int i = 0; i < (int) probs.size(); i++) {
  1037. cumsum += probs[i];
  1038. if (cumsum >= top_p) {
  1039. probs.resize(i + 1);
  1040. logits_id.resize(i + 1);
  1041. break;
  1042. }
  1043. }
  1044. cumsum = 1.0/cumsum;
  1045. for (int i = 0; i < (int) probs.size(); i++) {
  1046. probs[i] *= cumsum;
  1047. }
  1048. }
  1049. //printf("\n");
  1050. //for (int i = 0; i < (int) 10; i++) {
  1051. // printf("%d: '%s' %f\n", i, vocab.id_to_token.at(logits_id[i].second).c_str(), probs[i]);
  1052. //}
  1053. //printf("\n\n");
  1054. //exit(0);
  1055. std::discrete_distribution<> dist(probs.begin(), probs.end());
  1056. int idx = dist(rng);
  1057. return logits_id[idx].second;
  1058. }
  1059. //
  1060. // quantization
  1061. //
  1062. // TODO: reuse code from the llama_model_load() somehow
  1063. bool llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, int itype, int qk) {
  1064. ggml_type type = GGML_TYPE_Q4_1;
  1065. switch (itype) {
  1066. case 2: type = GGML_TYPE_Q4_0; break;
  1067. case 3: type = GGML_TYPE_Q4_1; break;
  1068. default: fprintf(stderr, "%s: invalid quantization type %d\n", __func__, itype); return 1;
  1069. };
  1070. if (type != GGML_TYPE_Q4_0 && type != GGML_TYPE_Q4_1) {
  1071. fprintf(stderr, "%s: invalid quantization type %d\n", __func__, type);
  1072. return false;
  1073. }
  1074. llama_vocab vocab;
  1075. printf("%s: loading model from '%s'\n", __func__, fname_inp.c_str());
  1076. auto finp = std::ifstream(fname_inp, std::ios::binary);
  1077. if (!finp) {
  1078. fprintf(stderr, "%s: failed to open '%s' for reading\n", __func__, fname_inp.c_str());
  1079. return false;
  1080. }
  1081. auto fout = std::ofstream(fname_out, std::ios::binary);
  1082. if (!fout) {
  1083. fprintf(stderr, "%s: failed to open '%s' for writing\n", __func__, fname_out.c_str());
  1084. return false;
  1085. }
  1086. // verify magic
  1087. {
  1088. uint32_t magic;
  1089. finp.read((char *) &magic, sizeof(magic));
  1090. if (magic == LLAMA_FILE_MAGIC_UNVERSIONED) {
  1091. fprintf(stderr, "%s: invalid model file '%s' (too old, regenerate your model files!)\n",
  1092. __func__, fname_inp.c_str());
  1093. return false;
  1094. }
  1095. if (magic != LLAMA_FILE_MAGIC) {
  1096. fprintf(stderr, "%s: invalid model file '%s' (bad magic)\n", __func__, fname_inp.c_str());
  1097. return false;
  1098. }
  1099. fout.write((char *) &magic, sizeof(magic));
  1100. uint32_t format_version;
  1101. finp.read((char *) &format_version, sizeof(format_version));
  1102. if (format_version != LLAMA_FILE_VERSION) {
  1103. fprintf(stderr, "%s: invalid model file '%s' (unsupported format version %" PRIu32 ", expected %d)\n",
  1104. __func__, fname_inp.c_str(), format_version, LLAMA_FILE_VERSION);
  1105. return false;
  1106. }
  1107. fout.write((char *) &format_version, sizeof(format_version));
  1108. }
  1109. llama_hparams hparams;
  1110. // load hparams
  1111. {
  1112. finp.read((char *) &hparams.n_vocab, sizeof(hparams.n_vocab));
  1113. //finp.read((char *) &hparams.n_ctx, sizeof(hparams.n_ctx));
  1114. finp.read((char *) &hparams.n_embd, sizeof(hparams.n_embd));
  1115. finp.read((char *) &hparams.n_mult, sizeof(hparams.n_mult));
  1116. finp.read((char *) &hparams.n_head, sizeof(hparams.n_head));
  1117. finp.read((char *) &hparams.n_layer, sizeof(hparams.n_layer));
  1118. finp.read((char *) &hparams.n_rot, sizeof(hparams.n_rot));
  1119. finp.read((char *) &hparams.f16, sizeof(hparams.f16));
  1120. printf("%s: n_vocab = %d\n", __func__, hparams.n_vocab);
  1121. printf("%s: n_ctx = %d\n", __func__, hparams.n_ctx);
  1122. printf("%s: n_embd = %d\n", __func__, hparams.n_embd);
  1123. printf("%s: n_mult = %d\n", __func__, hparams.n_mult);
  1124. printf("%s: n_head = %d\n", __func__, hparams.n_head);
  1125. printf("%s: n_layer = %d\n", __func__, hparams.n_layer);
  1126. printf("%s: f16 = %d\n", __func__, hparams.f16);
  1127. fout.write((char *) &hparams.n_vocab, sizeof(hparams.n_vocab));
  1128. //fout.write((char *) &hparams.n_ctx, sizeof(hparams.n_ctx));
  1129. fout.write((char *) &hparams.n_embd, sizeof(hparams.n_embd));
  1130. fout.write((char *) &hparams.n_mult, sizeof(hparams.n_mult));
  1131. fout.write((char *) &hparams.n_head, sizeof(hparams.n_head));
  1132. fout.write((char *) &hparams.n_layer, sizeof(hparams.n_layer));
  1133. fout.write((char *) &hparams.n_rot, sizeof(hparams.n_rot));
  1134. fout.write((char *) &itype, sizeof(hparams.f16));
  1135. }
  1136. // load vocab
  1137. {
  1138. const int32_t n_vocab = hparams.n_vocab;
  1139. if (n_vocab != hparams.n_vocab) {
  1140. fprintf(stderr, "%s: invalid model file '%s' (bad vocab size %d != %d)\n",
  1141. __func__, fname_inp.c_str(), n_vocab, hparams.n_vocab);
  1142. return false;
  1143. }
  1144. std::string word;
  1145. vocab.id_to_token.resize(n_vocab);
  1146. for (int i = 0; i < n_vocab; i++) {
  1147. uint32_t len;
  1148. finp.read ((char *) &len, sizeof(len));
  1149. fout.write((char *) &len, sizeof(len));
  1150. word.resize(len);
  1151. finp.read ((char *) word.data(), len);
  1152. fout.write((char *) word.data(), len);
  1153. float score;
  1154. finp.read ((char *) &score, sizeof(score));
  1155. fout.write((char *) &score, sizeof(score));
  1156. vocab.token_to_id[word] = i;
  1157. auto &tok_score = vocab.id_to_token[i];
  1158. tok_score.tok = word;
  1159. tok_score.score = score;
  1160. }
  1161. }
  1162. // load weights
  1163. {
  1164. size_t total_size_org = 0;
  1165. size_t total_size_new = 0;
  1166. std::vector<float> work;
  1167. std::vector<uint8_t> data_u8;
  1168. std::vector<ggml_fp16_t> data_f16;
  1169. std::vector<float> data_f32;
  1170. std::vector<int64_t> hist_all(1 << 4, 0);
  1171. while (true) {
  1172. int32_t n_dims;
  1173. int32_t length;
  1174. int32_t ftype;
  1175. finp.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  1176. finp.read(reinterpret_cast<char *>(&length), sizeof(length));
  1177. finp.read(reinterpret_cast<char *>(&ftype), sizeof(ftype));
  1178. if (finp.eof()) {
  1179. break;
  1180. }
  1181. int32_t nelements = 1;
  1182. int32_t ne[2] = { 1, 1 };
  1183. for (int i = 0; i < n_dims; ++i) {
  1184. finp.read (reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  1185. nelements *= ne[i];
  1186. }
  1187. std::string name(length, 0);
  1188. finp.read (&name[0], length);
  1189. {
  1190. static const char * ftype_str[] = { "f32", "f16", "q4_0", "q4_1", };
  1191. printf("%48s - [%5d, %5d], type = %6s ", name.data(), ne[0], ne[1], ftype_str[ftype]);
  1192. }
  1193. // regexes of tensor names to be quantized
  1194. const std::vector<std::string> k_names = {
  1195. ".*weight",
  1196. };
  1197. bool quantize = false;
  1198. for (const auto & s : k_names) {
  1199. if (std::regex_match(name, std::regex(s))) {
  1200. quantize = true;
  1201. break;
  1202. }
  1203. }
  1204. // quantize only 2D tensors
  1205. quantize &= (n_dims == 2);
  1206. if (quantize) {
  1207. if (ftype != 0 && ftype != 1) {
  1208. fprintf(stderr, "%s: unsupported ftype %d for integer quantization\n", __func__, ftype);
  1209. return false;
  1210. }
  1211. if (ftype == 1) {
  1212. data_f16.resize(nelements);
  1213. finp.read(reinterpret_cast<char *>(data_f16.data()), nelements * sizeof(ggml_fp16_t));
  1214. data_f32.resize(nelements);
  1215. for (int i = 0; i < nelements; ++i) {
  1216. data_f32[i] = ggml_fp16_to_fp32(data_f16[i]);
  1217. }
  1218. } else {
  1219. data_f32.resize(nelements);
  1220. finp.read(reinterpret_cast<char *>(data_f32.data()), nelements * sizeof(float));
  1221. }
  1222. ftype = itype;
  1223. } else {
  1224. const int bpe = (ftype == 0) ? sizeof(float) : sizeof(uint16_t);
  1225. data_u8.resize(nelements*bpe);
  1226. finp.read(reinterpret_cast<char *>(data_u8.data()), nelements * bpe);
  1227. }
  1228. fout.write(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  1229. fout.write(reinterpret_cast<char *>(&length), sizeof(length));
  1230. fout.write(reinterpret_cast<char *>(&ftype), sizeof(ftype));
  1231. for (int i = 0; i < n_dims; ++i) {
  1232. fout.write(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  1233. }
  1234. fout.write(&name[0], length);
  1235. if (quantize) {
  1236. printf("quantizing .. ");
  1237. work.resize(nelements); // for quantization
  1238. size_t cur_size = 0;
  1239. std::vector<int64_t> hist_cur(1 << 4, 0);
  1240. switch (type) {
  1241. case GGML_TYPE_Q4_0:
  1242. {
  1243. cur_size = ggml_quantize_q4_0(data_f32.data(), work.data(), nelements, ne[0], qk, hist_cur.data());
  1244. } break;
  1245. case GGML_TYPE_Q4_1:
  1246. {
  1247. cur_size = ggml_quantize_q4_1(data_f32.data(), work.data(), nelements, ne[0], qk, hist_cur.data());
  1248. } break;
  1249. default:
  1250. {
  1251. fprintf(stderr, "%s: unsupported quantization type %d\n", __func__, type);
  1252. return false;
  1253. }
  1254. }
  1255. fout.write(reinterpret_cast<char *>(work.data()), cur_size);
  1256. total_size_new += cur_size;
  1257. printf("size = %8.2f MB -> %8.2f MB | hist: ", nelements * sizeof(float)/1024.0/1024.0, cur_size/1024.0/1024.0);
  1258. for (int i = 0; i < (int) hist_cur.size(); ++i) {
  1259. hist_all[i] += hist_cur[i];
  1260. }
  1261. for (int i = 0; i < (int) hist_cur.size(); ++i) {
  1262. printf("%5.3f ", hist_cur[i] / (float)nelements);
  1263. }
  1264. printf("\n");
  1265. } else {
  1266. printf("size = %8.3f MB\n", data_u8.size()/1024.0/1024.0);
  1267. fout.write(reinterpret_cast<char *>(data_u8.data()), data_u8.size());
  1268. total_size_new += data_u8.size();
  1269. }
  1270. total_size_org += nelements * sizeof(float);
  1271. }
  1272. printf("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  1273. printf("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  1274. {
  1275. int64_t sum_all = 0;
  1276. for (int i = 0; i < (int) hist_all.size(); ++i) {
  1277. sum_all += hist_all[i];
  1278. }
  1279. printf("%s: hist: ", __func__);
  1280. for (int i = 0; i < (int) hist_all.size(); ++i) {
  1281. printf("%5.3f ", hist_all[i] / (float)sum_all);
  1282. }
  1283. printf("\n");
  1284. }
  1285. }
  1286. finp.close();
  1287. fout.close();
  1288. return true;
  1289. }
  1290. //
  1291. // interface implementation
  1292. //
  1293. struct llama_context * llama_init_from_file(
  1294. const char * path_model,
  1295. struct llama_context_params params) {
  1296. ggml_time_init();
  1297. llama_context * ctx = new llama_context;
  1298. if (params.seed <= 0) {
  1299. params.seed = time(NULL);
  1300. }
  1301. ctx->rng = std::mt19937(params.seed);
  1302. ctx->logits_all = params.logits_all;
  1303. ggml_type memory_type = params.f16_kv ? GGML_TYPE_F16 : GGML_TYPE_F32;
  1304. if (!llama_model_load(path_model, *ctx, params.n_ctx, params.n_parts, memory_type,
  1305. params.vocab_only, params.progress_callback,
  1306. params.progress_callback_user_data)) {
  1307. fprintf(stderr, "%s: failed to load model\n", __func__);
  1308. llama_free(ctx);
  1309. return nullptr;
  1310. }
  1311. if (params.use_mlock) {
  1312. char *err;
  1313. if (!ggml_mlock(ctx->model.ctx, &err)) {
  1314. fprintf(stderr, "%s\n", err);
  1315. free(err);
  1316. llama_free(ctx);
  1317. return nullptr;
  1318. }
  1319. }
  1320. // reserve memory for context buffers
  1321. {
  1322. if (!kv_cache_init(ctx->model.hparams, ctx->model.kv_self, memory_type, ctx->model.hparams.n_ctx)) {
  1323. fprintf(stderr, "%s: kv_cache_init() failed for self-attention cache\n", __func__);
  1324. llama_free(ctx);
  1325. return nullptr;
  1326. }
  1327. {
  1328. const size_t memory_size = ggml_nbytes(ctx->model.kv_self.k) + ggml_nbytes(ctx->model.kv_self.v);
  1329. fprintf(stderr, "%s: kv self size = %7.2f MB\n", __func__, memory_size / 1024.0 / 1024.0);
  1330. }
  1331. const auto & hparams = ctx->model.hparams;
  1332. if (params.logits_all) {
  1333. ctx->logits.reserve(hparams.n_ctx*hparams.n_vocab);
  1334. } else {
  1335. ctx->logits.reserve(hparams.n_ctx);
  1336. }
  1337. if (params.embedding){
  1338. ctx->embedding.reserve(hparams.n_embd);
  1339. }
  1340. ctx->buf_compute.resize(MEM_REQ_EVAL.at(ctx->model.type));
  1341. ctx->buf_scratch[0].resize(MEM_REQ_SCRATCH0.at(ctx->model.type));
  1342. ctx->buf_scratch[1].resize(MEM_REQ_SCRATCH1.at(ctx->model.type));
  1343. }
  1344. return ctx;
  1345. }
  1346. void llama_free(struct llama_context * ctx) {
  1347. kv_cache_free(ctx->model.kv_self);
  1348. if (ctx->model.ctx) {
  1349. ggml_free(ctx->model.ctx);
  1350. }
  1351. delete ctx;
  1352. }
  1353. int llama_model_quantize(
  1354. const char * fname_inp,
  1355. const char * fname_out,
  1356. int itype,
  1357. int qk) {
  1358. if (!llama_model_quantize_internal(fname_inp, fname_out, itype, qk)) {
  1359. fprintf(stderr, "%s: failed to quantize\n", __func__);
  1360. return 1;
  1361. }
  1362. return 0;
  1363. }
  1364. int llama_eval(
  1365. struct llama_context * ctx,
  1366. const llama_token * tokens,
  1367. int n_tokens,
  1368. int n_past,
  1369. int n_threads) {
  1370. if (!llama_eval_internal(*ctx, tokens, n_tokens, n_past, n_threads)) {
  1371. fprintf(stderr, "%s: failed to eval\n", __func__);
  1372. return 1;
  1373. }
  1374. return 0;
  1375. }
  1376. int llama_tokenize(
  1377. struct llama_context * ctx,
  1378. const char * text,
  1379. llama_token * tokens,
  1380. int n_max_tokens,
  1381. bool add_bos) {
  1382. auto res = llama_tokenize(ctx->vocab, text, add_bos);
  1383. if (n_max_tokens < (int) res.size()) {
  1384. fprintf(stderr, "%s: too many tokens\n", __func__);
  1385. return -((int) res.size());
  1386. }
  1387. for (size_t i = 0; i < res.size(); i++) {
  1388. tokens[i] = res[i];
  1389. }
  1390. return res.size();
  1391. }
  1392. int llama_n_vocab(struct llama_context * ctx) {
  1393. return ctx->vocab.id_to_token.size();
  1394. }
  1395. int llama_n_ctx(struct llama_context * ctx) {
  1396. return ctx->model.hparams.n_ctx;
  1397. }
  1398. float * llama_get_logits(struct llama_context * ctx) {
  1399. return ctx->logits.data();
  1400. }
  1401. float * llama_get_embeddings(struct llama_context * ctx) {
  1402. return ctx->embedding.data();
  1403. }
  1404. const char * llama_token_to_str(struct llama_context * ctx, llama_token token) {
  1405. if (token >= llama_n_vocab(ctx)) {
  1406. return nullptr;
  1407. }
  1408. return ctx->vocab.id_to_token[token].tok.c_str();
  1409. }
  1410. llama_token llama_token_bos() {
  1411. return 1;
  1412. }
  1413. llama_token llama_token_eos() {
  1414. return 2;
  1415. }
  1416. llama_token llama_sample_top_p_top_k(
  1417. llama_context * ctx,
  1418. const llama_token * last_n_tokens_data,
  1419. int last_n_tokens_size,
  1420. int top_k,
  1421. double top_p,
  1422. double temp,
  1423. double repeat_penalty) {
  1424. const int64_t t_start_sample_us = ggml_time_us();
  1425. llama_token result = 0;
  1426. // TODO: avoid this ...
  1427. const auto last_n_tokens = std::vector<llama_token>(last_n_tokens_data, last_n_tokens_data + last_n_tokens_size);
  1428. result = llama_sample_top_p_top_k(
  1429. *ctx,
  1430. last_n_tokens,
  1431. top_k,
  1432. top_p,
  1433. temp,
  1434. repeat_penalty);
  1435. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  1436. ctx->n_sample++;
  1437. return result;
  1438. }
  1439. void llama_print_timings(struct llama_context * ctx) {
  1440. const int64_t t_end_us = ggml_time_us();
  1441. const int32_t n_sample = std::max(1, ctx->n_sample);
  1442. const int32_t n_eval = std::max(1, ctx->n_eval);
  1443. const int32_t n_p_eval = std::max(1, ctx->n_p_eval);
  1444. fprintf(stderr, "\n");
  1445. fprintf(stderr, "%s: load time = %8.2f ms\n", __func__, ctx->t_load_us / 1000.0f);
  1446. 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);
  1447. 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);
  1448. 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);
  1449. fprintf(stderr, "%s: total time = %8.2f ms\n", __func__, (t_end_us - ctx->t_start_us)/1000.0f);
  1450. }
  1451. void llama_reset_timings(struct llama_context * ctx) {
  1452. ctx->t_start_us = ggml_time_us();
  1453. ctx->t_sample_us = ctx->n_sample = 0;
  1454. ctx->t_eval_us = ctx->n_eval = 0;
  1455. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  1456. }
  1457. const char * llama_print_system_info(void) {
  1458. static std::string s;
  1459. s = "";
  1460. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  1461. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  1462. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  1463. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  1464. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  1465. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  1466. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  1467. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  1468. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  1469. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  1470. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  1471. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  1472. return s.c_str();
  1473. }