main.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263
  1. #include "ggml.h"
  2. #include "utils.h"
  3. #include <cassert>
  4. #include <cinttypes>
  5. #include <cmath>
  6. #include <cstdio>
  7. #include <cstring>
  8. #include <fstream>
  9. #include <iostream>
  10. #include <string>
  11. #include <vector>
  12. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  13. #include <signal.h>
  14. #include <unistd.h>
  15. #elif defined (_WIN32)
  16. #include <signal.h>
  17. #endif
  18. #if defined (_WIN32)
  19. #pragma comment(lib,"kernel32.lib")
  20. extern "C" __declspec(dllimport) void* __stdcall GetStdHandle(unsigned long nStdHandle);
  21. extern "C" __declspec(dllimport) int __stdcall GetConsoleMode(void* hConsoleHandle, unsigned long* lpMode);
  22. extern "C" __declspec(dllimport) int __stdcall SetConsoleMode(void* hConsoleHandle, unsigned long dwMode);
  23. #endif
  24. #define ANSI_COLOR_RED "\x1b[31m"
  25. #define ANSI_COLOR_GREEN "\x1b[32m"
  26. #define ANSI_COLOR_YELLOW "\x1b[33m"
  27. #define ANSI_COLOR_BLUE "\x1b[34m"
  28. #define ANSI_COLOR_MAGENTA "\x1b[35m"
  29. #define ANSI_COLOR_CYAN "\x1b[36m"
  30. #define ANSI_COLOR_RESET "\x1b[0m"
  31. #define ANSI_BOLD "\x1b[1m"
  32. /* Keep track of current color of output, and emit ANSI code if it changes. */
  33. enum console_state {
  34. CONSOLE_STATE_DEFAULT=0,
  35. CONSOLE_STATE_PROMPT,
  36. CONSOLE_STATE_USER_INPUT
  37. };
  38. static console_state con_st = CONSOLE_STATE_DEFAULT;
  39. static bool con_use_color = false;
  40. void set_console_state(console_state new_st)
  41. {
  42. if (!con_use_color) return;
  43. // only emit color code if state changed
  44. if (new_st != con_st) {
  45. con_st = new_st;
  46. switch(con_st) {
  47. case CONSOLE_STATE_DEFAULT:
  48. printf(ANSI_COLOR_RESET);
  49. return;
  50. case CONSOLE_STATE_PROMPT:
  51. printf(ANSI_COLOR_YELLOW);
  52. return;
  53. case CONSOLE_STATE_USER_INPUT:
  54. printf(ANSI_BOLD ANSI_COLOR_GREEN);
  55. return;
  56. }
  57. }
  58. }
  59. static const int EOS_TOKEN_ID = 2;
  60. // determine number of model parts based on the dimension
  61. static const std::unordered_map<int, int> LLAMA_N_PARTS = {
  62. { 4096, 1 },
  63. { 5120, 2 },
  64. { 6656, 4 },
  65. { 8192, 8 },
  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_model {
  94. llama_hparams hparams;
  95. struct ggml_tensor * tok_embeddings;
  96. struct ggml_tensor * norm;
  97. struct ggml_tensor * output;
  98. std::vector<llama_layer> layers;
  99. // key + value memory
  100. struct ggml_tensor * memory_k;
  101. struct ggml_tensor * memory_v;
  102. //
  103. struct ggml_context * ctx;
  104. std::unordered_map<std::string, struct ggml_tensor *> tensors;
  105. };
  106. // load the model's weights from a file
  107. bool llama_model_load(const std::string & fname, llama_model & model, llama_vocab & vocab, int n_ctx, int n_parts, ggml_type memory_type = GGML_TYPE_F32) {
  108. fprintf(stderr, "%s: loading model from '%s' - please wait ...\n", __func__, fname.c_str());
  109. std::vector<char> f_buf(1024*1024);
  110. auto fin = std::ifstream(fname, std::ios::binary);
  111. fin.rdbuf()->pubsetbuf(f_buf.data(), f_buf.size());
  112. if (!fin) {
  113. fprintf(stderr, "%s: failed to open '%s'\n", __func__, fname.c_str());
  114. return false;
  115. }
  116. // verify magic
  117. {
  118. uint32_t magic;
  119. fin.read((char *) &magic, sizeof(magic));
  120. if (magic == FILE_MAGIC_UNVERSIONED) {
  121. fprintf(stderr, "%s: invalid model file '%s' (too old, regenerate your model files!)\n",
  122. __func__, fname.c_str());
  123. return false;
  124. }
  125. if (magic != FILE_MAGIC) {
  126. fprintf(stderr, "%s: invalid model file '%s' (bad magic)\n", __func__, fname.c_str());
  127. return false;
  128. }
  129. uint32_t format_version;
  130. fin.read((char *) &format_version, sizeof(format_version));
  131. if (format_version != FILE_VERSION) {
  132. fprintf(stderr, "%s: invalid model file '%s' (unsupported format version %" PRIu32 ", expected %d)\n",
  133. __func__, fname.c_str(), format_version, FILE_VERSION);
  134. return false;
  135. }
  136. }
  137. int n_ff = 0;
  138. // load hparams
  139. {
  140. auto & hparams = model.hparams;
  141. fin.read((char *) &hparams.n_vocab, sizeof(hparams.n_vocab));
  142. //fin.read((char *) &hparams.n_ctx, sizeof(hparams.n_ctx));
  143. fin.read((char *) &hparams.n_embd, sizeof(hparams.n_embd));
  144. fin.read((char *) &hparams.n_mult, sizeof(hparams.n_mult));
  145. fin.read((char *) &hparams.n_head, sizeof(hparams.n_head));
  146. fin.read((char *) &hparams.n_layer, sizeof(hparams.n_layer));
  147. fin.read((char *) &hparams.n_rot, sizeof(hparams.n_rot));
  148. fin.read((char *) &hparams.f16, sizeof(hparams.f16));
  149. hparams.n_ctx = n_ctx;
  150. n_ff = ((2*(4*hparams.n_embd)/3 + hparams.n_mult - 1)/hparams.n_mult)*hparams.n_mult;
  151. if (n_parts < 1) {
  152. n_parts = LLAMA_N_PARTS.at(hparams.n_embd);
  153. }
  154. // temp warning to tell the user to use "--n_parts"
  155. if (hparams.f16 == 4 && n_parts != 1) {
  156. 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);
  157. fprintf(stderr, "%s: use '--n_parts 1' if necessary\n", __func__);
  158. }
  159. fprintf(stderr, "%s: n_vocab = %d\n", __func__, hparams.n_vocab);
  160. fprintf(stderr, "%s: n_ctx = %d\n", __func__, hparams.n_ctx);
  161. fprintf(stderr, "%s: n_embd = %d\n", __func__, hparams.n_embd);
  162. fprintf(stderr, "%s: n_mult = %d\n", __func__, hparams.n_mult);
  163. fprintf(stderr, "%s: n_head = %d\n", __func__, hparams.n_head);
  164. fprintf(stderr, "%s: n_layer = %d\n", __func__, hparams.n_layer);
  165. fprintf(stderr, "%s: n_rot = %d\n", __func__, hparams.n_rot);
  166. fprintf(stderr, "%s: f16 = %d\n", __func__, hparams.f16);
  167. fprintf(stderr, "%s: n_ff = %d\n", __func__, n_ff);
  168. fprintf(stderr, "%s: n_parts = %d\n", __func__, n_parts);
  169. }
  170. // load vocab
  171. {
  172. std::string word;
  173. vocab.id_to_token.resize(model.hparams.n_vocab);
  174. std::vector<char> tmp(64);
  175. for (int i = 0; i < model.hparams.n_vocab; i++) {
  176. uint32_t len;
  177. fin.read((char *) &len, sizeof(len));
  178. word.resize(len);
  179. if (len > 0) {
  180. tmp.resize(len);
  181. fin.read(tmp.data(), len);
  182. word.assign(tmp.data(), len);
  183. } else {
  184. word.clear();
  185. }
  186. float score;
  187. fin.read((char *) &score, sizeof(score));
  188. vocab.token_to_id[word] = i;
  189. auto &tok_score = vocab.id_to_token[i];
  190. tok_score.tok = word;
  191. tok_score.score = score;
  192. }
  193. }
  194. // for the big tensors, we have the option to store the data in 16-bit floats or quantized
  195. // in order to save memory and also to speed up the computation
  196. // wtype is for per-layer weights, while vtype is for other weights
  197. ggml_type wtype, vtype;
  198. switch (model.hparams.f16) {
  199. case 0: wtype = vtype = GGML_TYPE_F32; break;
  200. case 1: wtype = vtype = GGML_TYPE_F16; break;
  201. case 2: wtype = vtype = GGML_TYPE_Q4_0; break;
  202. case 3: wtype = vtype = GGML_TYPE_Q4_1; break;
  203. case 4: wtype = GGML_TYPE_Q4_1; vtype = GGML_TYPE_F16; break;
  204. default:
  205. {
  206. fprintf(stderr, "%s: invalid model file '%s' (bad f16 value %d)\n",
  207. __func__, fname.c_str(), model.hparams.f16);
  208. return false;
  209. }
  210. }
  211. auto & ctx = model.ctx;
  212. size_t ctx_size = 0;
  213. {
  214. const auto & hparams = model.hparams;
  215. const int n_embd = hparams.n_embd;
  216. const int n_layer = hparams.n_layer;
  217. const int n_ctx = hparams.n_ctx;
  218. const int n_vocab = hparams.n_vocab;
  219. ctx_size += n_embd*n_vocab*ggml_type_sizef(vtype); // tok_embeddings
  220. ctx_size += n_embd*ggml_type_sizef(GGML_TYPE_F32); // norm
  221. ctx_size += n_embd*n_vocab*ggml_type_sizef(vtype); // output
  222. ctx_size += n_layer*(n_embd*ggml_type_sizef(GGML_TYPE_F32)); // attention_norm
  223. ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // wq
  224. ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // wk
  225. ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // wv
  226. ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // wo
  227. ctx_size += n_layer*(n_embd*ggml_type_sizef(GGML_TYPE_F32)); // ffn_norm
  228. ctx_size += n_layer*(n_ff*n_embd*ggml_type_sizef(wtype)); // w1
  229. ctx_size += n_layer*(n_ff*n_embd*ggml_type_sizef(wtype)); // w2
  230. ctx_size += n_layer*(n_ff*n_embd*ggml_type_sizef(wtype)); // w3
  231. ctx_size += n_ctx*n_layer*n_embd*ggml_type_sizef(memory_type); // memory_k
  232. ctx_size += n_ctx*n_layer*n_embd*ggml_type_sizef(memory_type); // memory_v
  233. ctx_size += (5 + 10*n_layer)*256; // object overhead
  234. fprintf(stderr, "%s: ggml ctx size = %6.2f MB\n", __func__, ctx_size/(1024.0*1024.0));
  235. }
  236. // create the ggml context
  237. {
  238. struct ggml_init_params params = {
  239. /*.mem_size =*/ ctx_size,
  240. /*.mem_buffer =*/ NULL,
  241. };
  242. model.ctx = ggml_init(params);
  243. if (!model.ctx) {
  244. fprintf(stderr, "%s: ggml_init() failed\n", __func__);
  245. return false;
  246. }
  247. }
  248. // prepare memory for the weights
  249. {
  250. const auto & hparams = model.hparams;
  251. const int n_embd = hparams.n_embd;
  252. const int n_layer = hparams.n_layer;
  253. const int n_vocab = hparams.n_vocab;
  254. model.layers.resize(n_layer);
  255. model.tok_embeddings = ggml_new_tensor_2d(ctx, vtype, n_embd, n_vocab);
  256. model.norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  257. model.output = ggml_new_tensor_2d(ctx, vtype, n_embd, n_vocab);
  258. // map by name
  259. model.tensors["tok_embeddings.weight"] = model.tok_embeddings;
  260. model.tensors["norm.weight"] = model.norm;
  261. model.tensors["output.weight"] = model.output;
  262. for (int i = 0; i < n_layer; ++i) {
  263. auto & layer = model.layers[i];
  264. layer.attention_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  265. layer.wq = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  266. layer.wk = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  267. layer.wv = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  268. layer.wo = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  269. layer.ffn_norm = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  270. layer.w1 = ggml_new_tensor_2d(ctx, wtype, n_embd, n_ff);
  271. layer.w2 = ggml_new_tensor_2d(ctx, wtype, n_ff, n_embd);
  272. layer.w3 = ggml_new_tensor_2d(ctx, wtype, n_embd, n_ff);
  273. // map by name
  274. model.tensors["layers." + std::to_string(i) + ".attention_norm.weight"] = layer.attention_norm;
  275. model.tensors["layers." + std::to_string(i) + ".attention.wq.weight"] = layer.wq;
  276. model.tensors["layers." + std::to_string(i) + ".attention.wk.weight"] = layer.wk;
  277. model.tensors["layers." + std::to_string(i) + ".attention.wv.weight"] = layer.wv;
  278. model.tensors["layers." + std::to_string(i) + ".attention.wo.weight"] = layer.wo;
  279. model.tensors["layers." + std::to_string(i) + ".ffn_norm.weight"] = layer.ffn_norm;
  280. model.tensors["layers." + std::to_string(i) + ".feed_forward.w1.weight"] = layer.w1;
  281. model.tensors["layers." + std::to_string(i) + ".feed_forward.w2.weight"] = layer.w2;
  282. model.tensors["layers." + std::to_string(i) + ".feed_forward.w3.weight"] = layer.w3;
  283. }
  284. }
  285. // key + value memory
  286. {
  287. const auto & hparams = model.hparams;
  288. const int n_embd = hparams.n_embd;
  289. const int n_layer = hparams.n_layer;
  290. const int n_ctx = hparams.n_ctx;
  291. const int n_mem = n_layer*n_ctx;
  292. const int n_elements = n_embd*n_mem;
  293. model.memory_k = ggml_new_tensor_1d(ctx, memory_type, n_elements);
  294. model.memory_v = ggml_new_tensor_1d(ctx, memory_type, n_elements);
  295. const size_t memory_size = ggml_nbytes(model.memory_k) + ggml_nbytes(model.memory_v);
  296. fprintf(stderr, "%s: memory_size = %8.2f MB, n_mem = %d\n", __func__, memory_size/1024.0/1024.0, n_mem);
  297. }
  298. const size_t file_offset = fin.tellg();
  299. fin.close();
  300. std::vector<uint8_t> tmp;
  301. for (int i = 0; i < n_parts; ++i) {
  302. const int part_id = i;
  303. //const int part_id = n_parts - i - 1;
  304. std::string fname_part = fname;
  305. if (i > 0) {
  306. fname_part += "." + std::to_string(i);
  307. }
  308. fprintf(stderr, "%s: loading model part %d/%d from '%s'\n", __func__, i+1, n_parts, fname_part.c_str());
  309. fin = std::ifstream(fname_part, std::ios::binary);
  310. fin.rdbuf()->pubsetbuf(f_buf.data(), f_buf.size());
  311. fin.seekg(file_offset);
  312. // load weights
  313. {
  314. int n_tensors = 0;
  315. size_t total_size = 0;
  316. fprintf(stderr, "%s: ", __func__);
  317. while (true) {
  318. int32_t n_dims;
  319. int32_t length;
  320. int32_t ftype;
  321. fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  322. fin.read(reinterpret_cast<char *>(&length), sizeof(length));
  323. fin.read(reinterpret_cast<char *>(&ftype), sizeof(ftype));
  324. if (fin.eof()) {
  325. break;
  326. }
  327. int32_t nelements = 1;
  328. int32_t ne[2] = { 1, 1 };
  329. for (int i = 0; i < n_dims; ++i) {
  330. fin.read(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  331. nelements *= ne[i];
  332. }
  333. std::string name(length, 0);
  334. fin.read(&name[0], length);
  335. if (model.tensors.find(name.data()) == model.tensors.end()) {
  336. fprintf(stderr, "%s: unknown tensor '%s' in model file\n", __func__, name.data());
  337. return false;
  338. }
  339. // split_type = 0: split by columns
  340. // split_type = 1: split by rows
  341. int split_type = 0;
  342. // split_type = 0:
  343. // regex:
  344. // - tok_embeddings.*
  345. // - layers.*.attention.wo.weight
  346. // - layers.*.feed_forward.w2.weight
  347. // split_type = 1:
  348. // regex:
  349. // - output.*
  350. // - layers.*.attention.wq.weight
  351. // - layers.*.attention.wk.weight
  352. // - layers.*.attention.wv.weight
  353. // - layers.*.feed_forward.w1.weight
  354. // - layers.*.feed_forward.w3.weight
  355. if (name.find("tok_embeddings") != std::string::npos) {
  356. split_type = 0;
  357. } else if (name.find("layers") != std::string::npos) {
  358. if (name.find("attention.wo.weight") != std::string::npos) {
  359. split_type = 0;
  360. } else if (name.find("feed_forward.w2.weight") != std::string::npos) {
  361. split_type = 0;
  362. } else {
  363. split_type = 1;
  364. }
  365. } else if (name.find("output") != std::string::npos) {
  366. split_type = 1;
  367. }
  368. auto tensor = model.tensors[name.data()];
  369. if (n_dims == 1) {
  370. if (ggml_nelements(tensor) != nelements) {
  371. fprintf(stderr, "%s: tensor '%s' has wrong size in model file\n", __func__, name.data());
  372. return false;
  373. }
  374. } else {
  375. if (ggml_nelements(tensor)/n_parts != nelements) {
  376. fprintf(stderr, "%s: tensor '%s' has wrong size in model file\n", __func__, name.data());
  377. return false;
  378. }
  379. }
  380. if (n_dims == 1) {
  381. if (tensor->ne[0] != ne[0] || tensor->ne[1] != ne[1]) {
  382. fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%d, %d], expected [%d, %d]\n",
  383. __func__, name.data(), tensor->ne[0], tensor->ne[1], ne[0], ne[1]);
  384. return false;
  385. }
  386. } else {
  387. if (split_type == 0) {
  388. if (tensor->ne[0]/n_parts != ne[0] || tensor->ne[1] != ne[1]) {
  389. fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%d, %d], expected [%d, %d]\n",
  390. __func__, name.data(), tensor->ne[0]/n_parts, tensor->ne[1], ne[0], ne[1]);
  391. return false;
  392. }
  393. } else {
  394. if (tensor->ne[0] != ne[0] || tensor->ne[1]/n_parts != ne[1]) {
  395. fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%d, %d], expected [%d, %d]\n",
  396. __func__, name.data(), tensor->ne[0], tensor->ne[1]/n_parts, ne[0], ne[1]);
  397. return false;
  398. }
  399. }
  400. }
  401. if (0) {
  402. static const char * ftype_str[] = { "f32", "f16", "q4_0", "q4_1", };
  403. fprintf(stderr, "%24s - [%5d, %5d], type = %6s, split = %d\n", name.data(), ne[0], ne[1], ftype_str[ftype], split_type);
  404. }
  405. size_t bpe = 0;
  406. switch (ftype) {
  407. case 0: bpe = ggml_type_size(GGML_TYPE_F32); break;
  408. case 1: bpe = ggml_type_size(GGML_TYPE_F16); break;
  409. case 2: bpe = ggml_type_size(GGML_TYPE_Q4_0); assert(ne[0] % 64 == 0); break;
  410. case 3: bpe = ggml_type_size(GGML_TYPE_Q4_1); assert(ne[0] % 64 == 0); break;
  411. default:
  412. {
  413. fprintf(stderr, "%s: unknown ftype %d in model file\n", __func__, ftype);
  414. return false;
  415. }
  416. };
  417. if (n_dims == 1 || n_parts == 1) {
  418. if ((nelements*bpe)/ggml_blck_size(tensor->type) != ggml_nbytes(tensor)) {
  419. fprintf(stderr, "%s: tensor '%s' has wrong size in model file: got %zu, expected %zu\n",
  420. __func__, name.data(), ggml_nbytes(tensor), nelements*bpe);
  421. return false;
  422. }
  423. if (part_id == 0) {
  424. fin.read(reinterpret_cast<char *>(tensor->data), ggml_nbytes(tensor));
  425. } else {
  426. fin.seekg(ggml_nbytes(tensor), std::ios::cur);
  427. }
  428. total_size += ggml_nbytes(tensor);
  429. } else {
  430. if ((nelements*bpe)/ggml_blck_size(tensor->type) != ggml_nbytes(tensor)/n_parts) {
  431. fprintf(stderr, "%s: tensor '%s' has wrong size in model file: got %zu, expected %zu\n",
  432. __func__, name.data(), ggml_nbytes(tensor)/n_parts, nelements*bpe);
  433. return false;
  434. }
  435. if (split_type == 0) {
  436. const int np0 = ne[0];
  437. const size_t row_size = (tensor->ne[0]/ggml_blck_size(tensor->type))*ggml_type_size(tensor->type);
  438. assert(row_size == tensor->nb[1]);
  439. for (int i1 = 0; i1 < ne[1]; ++i1) {
  440. const size_t offset_row = i1*row_size;
  441. const size_t offset = offset_row + ((part_id*np0)/ggml_blck_size(tensor->type))*ggml_type_size(tensor->type);
  442. fin.read(reinterpret_cast<char *>(tensor->data) + offset, row_size/n_parts);
  443. }
  444. } else {
  445. const int np1 = ne[1];
  446. const size_t row_size = (tensor->ne[0]/ggml_blck_size(tensor->type))*ggml_type_size(tensor->type);
  447. for (int i1 = 0; i1 < ne[1]; ++i1) {
  448. const size_t offset_row = (i1 + part_id*np1)*row_size;
  449. fin.read(reinterpret_cast<char *>(tensor->data) + offset_row, row_size);
  450. }
  451. }
  452. total_size += ggml_nbytes(tensor)/n_parts;
  453. }
  454. //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);
  455. if (++n_tensors % 8 == 0) {
  456. fprintf(stderr, ".");
  457. fflush(stderr);
  458. }
  459. }
  460. fprintf(stderr, " done\n");
  461. fprintf(stderr, "%s: model size = %8.2f MB / num tensors = %d\n", __func__, total_size/1024.0/1024.0, n_tensors);
  462. }
  463. fin.close();
  464. }
  465. return true;
  466. }
  467. // evaluate the transformer
  468. //
  469. // - model: the model
  470. // - n_threads: number of threads to use
  471. // - n_past: the context size so far
  472. // - embd_inp: the embeddings of the tokens in the context
  473. // - embd_w: the predicted logits for the next token
  474. //
  475. // The GPT-J model requires about 16MB of memory per input token.
  476. //
  477. bool llama_eval(
  478. const llama_model & model,
  479. const int n_threads,
  480. const int n_past,
  481. const std::vector<llama_vocab::id> & embd_inp,
  482. std::vector<float> & embd_w,
  483. size_t & mem_per_token,
  484. bool return_all_logits = false) {
  485. const int N = embd_inp.size();
  486. const auto & hparams = model.hparams;
  487. const int n_embd = hparams.n_embd;
  488. const int n_layer = hparams.n_layer;
  489. const int n_ctx = hparams.n_ctx;
  490. const int n_head = hparams.n_head;
  491. const int n_vocab = hparams.n_vocab;
  492. const int n_rot = hparams.n_embd/hparams.n_head;
  493. // TODO: check if this size scales with n_ctx linearly and remove constant. somehow I feel it wasn't the case
  494. // static size_t buf_size = hparams.n_ctx*1024*1024;
  495. static size_t buf_size = 512u*1024*1024;
  496. static void * buf = malloc(buf_size);
  497. if (mem_per_token > 0 && mem_per_token*N > buf_size) {
  498. const size_t buf_size_new = 1.3*(mem_per_token*N); // add 30% to account for ggml object overhead
  499. //fprintf(stderr, "\n%s: reallocating buffer from %zu to %zu bytes\n", __func__, buf_size, buf_size_new);
  500. // reallocate
  501. buf_size = buf_size_new;
  502. buf = realloc(buf, buf_size);
  503. if (buf == nullptr) {
  504. fprintf(stderr, "%s: failed to allocate %zu bytes\n", __func__, buf_size);
  505. return false;
  506. }
  507. }
  508. struct ggml_init_params params = {
  509. /*.mem_size =*/ buf_size,
  510. /*.mem_buffer =*/ buf,
  511. };
  512. struct ggml_context * ctx0 = ggml_init(params);
  513. ggml_cgraph gf = {};
  514. gf.n_threads = n_threads;
  515. struct ggml_tensor * embd = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  516. memcpy(embd->data, embd_inp.data(), N*ggml_element_size(embd));
  517. struct ggml_tensor * inpL = ggml_get_rows(ctx0, model.tok_embeddings, embd);
  518. for (int il = 0; il < n_layer; ++il) {
  519. struct ggml_tensor * inpSA = inpL;
  520. struct ggml_tensor * cur;
  521. // norm
  522. {
  523. cur = ggml_rms_norm(ctx0, inpL);
  524. // cur = attention_norm*cur
  525. cur = ggml_mul(ctx0,
  526. ggml_repeat(ctx0, model.layers[il].attention_norm, cur),
  527. cur);
  528. }
  529. // self-attention
  530. {
  531. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  532. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  533. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  534. // store key and value to memory
  535. if (N >= 1) {
  536. struct ggml_tensor * k = ggml_view_1d(ctx0, model.memory_k, N*n_embd, (ggml_element_size(model.memory_k)*n_embd)*(il*n_ctx + n_past));
  537. struct ggml_tensor * v = ggml_view_1d(ctx0, model.memory_v, N*n_embd, (ggml_element_size(model.memory_v)*n_embd)*(il*n_ctx + n_past));
  538. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Kcur, k));
  539. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Vcur, v));
  540. }
  541. // Q = Qcur.contiguous().view(n_embd/n_head, n_head, N).permute(0, 2, 1, 3)
  542. struct ggml_tensor * Q =
  543. ggml_permute(ctx0,
  544. ggml_rope(ctx0,
  545. ggml_cpy(ctx0,
  546. Qcur,
  547. ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_embd/n_head, n_head, N)),
  548. n_past, n_rot, 0),
  549. 0, 2, 1, 3);
  550. // K = Kmem.view(n_embd/n_head, n_head, n_past + N).permute(0, 2, 1, 3)
  551. struct ggml_tensor * K =
  552. ggml_permute(ctx0,
  553. ggml_rope(ctx0,
  554. ggml_reshape_3d(ctx0,
  555. ggml_view_1d(ctx0, model.memory_k, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(model.memory_k)*n_embd),
  556. n_embd/n_head, n_head, n_past + N),
  557. n_past, n_rot, 1),
  558. 0, 2, 1, 3);
  559. // K * Q
  560. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
  561. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  562. struct ggml_tensor * KQ_scaled =
  563. ggml_scale(ctx0,
  564. KQ,
  565. ggml_new_f32(ctx0, 1.0f/sqrt(float(n_embd)/n_head))
  566. );
  567. // KQ_masked = mask_past(KQ_scaled)
  568. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
  569. // KQ = soft_max(KQ_masked)
  570. struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
  571. // V_trans = Vmem.view(n_embd/n_head, n_head, n_past + N).permute(1, 2, 0, 3).contiguous()
  572. struct ggml_tensor * V_trans =
  573. ggml_permute(ctx0,
  574. ggml_reshape_3d(ctx0,
  575. ggml_view_1d(ctx0, model.memory_v, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(model.memory_v)*n_embd),
  576. n_embd/n_head, n_head, n_past + N),
  577. 1, 2, 0, 3);
  578. // KQV = transpose(V) * KQ_soft_max
  579. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V_trans, KQ_soft_max);
  580. // KQV_merged = KQV.permute(0, 2, 1, 3)
  581. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  582. // cur = KQV_merged.contiguous().view(n_embd, N)
  583. cur = ggml_cpy(ctx0,
  584. KQV_merged,
  585. ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  586. // projection (no bias)
  587. cur = ggml_mul_mat(ctx0,
  588. model.layers[il].wo,
  589. cur);
  590. }
  591. struct ggml_tensor * inpFF = ggml_add(ctx0, cur, inpSA);
  592. // feed-forward network
  593. {
  594. // norm
  595. {
  596. cur = ggml_rms_norm(ctx0, inpFF);
  597. // cur = ffn_norm*cur
  598. cur = ggml_mul(ctx0,
  599. ggml_repeat(ctx0, model.layers[il].ffn_norm, cur),
  600. cur);
  601. }
  602. struct ggml_tensor * tmp = ggml_mul_mat(ctx0,
  603. model.layers[il].w3,
  604. cur);
  605. cur = ggml_mul_mat(ctx0,
  606. model.layers[il].w1,
  607. cur);
  608. // SILU activation
  609. cur = ggml_silu(ctx0, cur);
  610. cur = ggml_mul(ctx0, cur, tmp);
  611. cur = ggml_mul_mat(ctx0,
  612. model.layers[il].w2,
  613. cur);
  614. }
  615. cur = ggml_add(ctx0, cur, inpFF);
  616. // input for next layer
  617. inpL = cur;
  618. }
  619. // norm
  620. {
  621. inpL = ggml_rms_norm(ctx0, inpL);
  622. // inpL = norm*inpL
  623. inpL = ggml_mul(ctx0,
  624. ggml_repeat(ctx0, model.norm, inpL),
  625. inpL);
  626. }
  627. // lm_head
  628. {
  629. inpL = ggml_mul_mat(ctx0, model.output, inpL);
  630. }
  631. // logits -> probs
  632. //inpL = ggml_soft_max(ctx0, inpL);
  633. // run the computation
  634. ggml_build_forward_expand(&gf, inpL);
  635. ggml_graph_compute (ctx0, &gf);
  636. //if (n_past%100 == 0) {
  637. // ggml_graph_print (&gf);
  638. // ggml_graph_dump_dot(&gf, NULL, "gpt-2.dot");
  639. //}
  640. //embd_w.resize(n_vocab*N);
  641. //memcpy(embd_w.data(), ggml_get_data(inpL), sizeof(float)*n_vocab*N);
  642. if (return_all_logits) {
  643. embd_w.resize(n_vocab * N);
  644. memcpy(embd_w.data(), (float *) ggml_get_data(inpL), sizeof(float)*n_vocab*N);
  645. } else {
  646. // return result for just the last token
  647. embd_w.resize(n_vocab);
  648. memcpy(embd_w.data(), (float *) ggml_get_data(inpL) + (n_vocab*(N-1)), sizeof(float)*n_vocab);
  649. }
  650. if (mem_per_token == 0) {
  651. mem_per_token = ggml_used_mem(ctx0)/N;
  652. }
  653. //fprintf(stderr, "used_mem = %zu\n", ggml_used_mem(ctx0));
  654. ggml_free(ctx0);
  655. return true;
  656. }
  657. std::vector<double> softmax(const std::vector<float>& logits) {
  658. std::vector<double> probs(logits.size());
  659. float max_logit = logits[0];
  660. for (float v : logits) max_logit = std::max(max_logit, v);
  661. double sum_exp = 0.0;
  662. for (size_t i = 0; i < logits.size(); i++) {
  663. // Subtract the maximum logit value from the current logit value for numerical stability
  664. float logit = logits[i] - max_logit;
  665. double exp_logit = std::exp(logit);
  666. sum_exp += exp_logit;
  667. probs[i] = exp_logit;
  668. }
  669. for (size_t i = 0; i < probs.size(); i++) probs[i] /= sum_exp;
  670. return probs;
  671. }
  672. void perplexity(const llama_vocab &vocab, const llama_model &model, const gpt_params &params, size_t mem_per_token) {
  673. // Download: https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-raw-v1.zip?ref=salesforce-research
  674. // Run `./main --perplexity -m models/7B/ggml-model-q4_0.bin -f wiki.test.raw`
  675. // Output: `perplexity: 13.5106 [114/114]`
  676. std::vector<llama_vocab::id> tokens = ::llama_tokenize(vocab, params.prompt, true);
  677. int count = 0;
  678. double nll = 0.0;
  679. int seq_count = tokens.size() / params.n_ctx;
  680. printf("Calculating perplexity over %d chunks\n", seq_count);
  681. for (int i = 0; i < seq_count; ++i) {
  682. int start = i * params.n_ctx;
  683. int end = start + params.n_ctx - 1;
  684. std::vector<llama_vocab::id> embd(tokens.begin() + start, tokens.begin() + end);
  685. std::vector<float> logits;
  686. auto start_t = std::chrono::high_resolution_clock::now();
  687. if (!llama_eval(model, params.n_threads, 0, embd, logits, mem_per_token, true)) {
  688. fprintf(stderr, "Failed to predict\n");
  689. return;
  690. }
  691. auto end_t = std::chrono::high_resolution_clock::now();
  692. if (i == 0) {
  693. double seconds = std::chrono::duration<double>(end_t - start_t).count();
  694. printf("%.2f seconds per pass - ETA %.2f hours\n", seconds, (seconds * seq_count) / (60.0*60.0));
  695. }
  696. // We get the logits for all the tokens in the context window (params.n_ctx)
  697. // from llama_eval above. Now, based on https://huggingface.co/docs/transformers/perplexity,
  698. // calculate the perplexity over the last half the window (so the model always has
  699. // some context to predict the token).
  700. //
  701. // We rely on the fact that attention in the forward pass only looks at previous
  702. // tokens here, so the logits returned for each token are an accurate representation
  703. // of what the model would have predicted at that point.
  704. //
  705. // Example, we have a context window of 512, we will compute perplexity for each of the
  706. // last 256 tokens. Then, we split the input up into context window size chunks to
  707. // process the entire prompt.
  708. for (int j = params.n_ctx / 2; j < params.n_ctx - 1; ++j) {
  709. // Calculate probability of next token, given the previous ones.
  710. int n_vocab = model.hparams.n_vocab;
  711. std::vector<float> tok_logits(
  712. logits.begin() + j * n_vocab,
  713. logits.begin() + (j + 1) * n_vocab);
  714. double prob = softmax(tok_logits)[tokens[start + j + 1]];
  715. nll += -std::log(prob);
  716. ++count;
  717. }
  718. // perplexity is e^(average negative log-likelihood)
  719. printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
  720. fflush(stdout);
  721. }
  722. printf("\n");
  723. }
  724. static bool is_interacting = false;
  725. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  726. void sigint_handler(int signo) {
  727. set_console_state(CONSOLE_STATE_DEFAULT);
  728. printf("\n"); // this also force flush stdout.
  729. if (signo == SIGINT) {
  730. if (!is_interacting) {
  731. is_interacting=true;
  732. } else {
  733. _exit(130);
  734. }
  735. }
  736. }
  737. #endif
  738. const char * llama_print_system_info(void) {
  739. static std::string s;
  740. s = "";
  741. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  742. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  743. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  744. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  745. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  746. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  747. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  748. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  749. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  750. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  751. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  752. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  753. return s.c_str();
  754. }
  755. int main(int argc, char ** argv) {
  756. ggml_time_init();
  757. const int64_t t_main_start_us = ggml_time_us();
  758. gpt_params params;
  759. params.model = "models/llama-7B/ggml-model.bin";
  760. if (gpt_params_parse(argc, argv, params) == false) {
  761. return 1;
  762. }
  763. if (params.n_ctx > 2048) {
  764. fprintf(stderr, "%s: warning: model does not support context sizes greater than 2048 tokens (%d specified);"
  765. "expect poor results\n", __func__, params.n_ctx);
  766. }
  767. if (params.seed < 0) {
  768. params.seed = time(NULL);
  769. }
  770. fprintf(stderr, "%s: seed = %d\n", __func__, params.seed);
  771. std::mt19937 rng(params.seed);
  772. if (params.random_prompt) {
  773. params.prompt = gpt_random_prompt(rng);
  774. }
  775. // save choice to use color for later
  776. // (note for later: this is a slightly awkward choice)
  777. con_use_color = params.use_color;
  778. // params.prompt = R"(// this function checks if the number n is prime
  779. //bool is_prime(int n) {)";
  780. int64_t t_load_us = 0;
  781. llama_vocab vocab;
  782. llama_model model;
  783. // load the model
  784. {
  785. const ggml_type memory_type = params.memory_f16 ? GGML_TYPE_F16 : GGML_TYPE_F32;
  786. const int64_t t_start_us = ggml_time_us();
  787. if (!llama_model_load(params.model, model, vocab, params.n_ctx, params.n_parts, memory_type)) {
  788. fprintf(stderr, "%s: failed to load model from '%s'\n", __func__, params.model.c_str());
  789. return 1;
  790. }
  791. t_load_us = ggml_time_us() - t_start_us;
  792. }
  793. // print system information
  794. {
  795. fprintf(stderr, "\n");
  796. fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
  797. params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
  798. }
  799. std::vector<float> logits;
  800. // determine the required inference memory per token:
  801. size_t mem_per_token = 0;
  802. llama_eval(model, params.n_threads, 0, { 0, 1, 2, 3 }, logits, mem_per_token);
  803. if (params.perplexity) {
  804. perplexity(vocab, model, params, mem_per_token);
  805. exit(0);
  806. }
  807. int n_past = 0;
  808. int64_t t_sample_us = 0;
  809. int64_t t_predict_us = 0;
  810. // Add a space in front of the first character to match OG llama tokenizer behavior
  811. params.prompt.insert(0, 1, ' ');
  812. // tokenize the prompt
  813. std::vector<llama_vocab::id> embd_inp = ::llama_tokenize(vocab, params.prompt, true);
  814. params.n_predict = std::min(params.n_predict, model.hparams.n_ctx - (int) embd_inp.size());
  815. // prefix & suffix for instruct mode
  816. const std::vector<llama_vocab::id> inp_pfx = ::llama_tokenize(vocab, "\n\n### Instruction:\n\n", true);
  817. const std::vector<llama_vocab::id> inp_sfx = ::llama_tokenize(vocab, "\n\n### Response:\n\n", false);
  818. // in instruct mode, we inject a prefix and a suffix to each input by the user
  819. if (params.instruct) {
  820. params.interactive = true;
  821. params.antiprompt.push_back("### Instruction:\n\n");
  822. }
  823. // enable interactive mode if reverse prompt is specified
  824. if (params.antiprompt.size() != 0) {
  825. params.interactive = true;
  826. }
  827. fprintf(stderr, "\n");
  828. fprintf(stderr, "%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  829. fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  830. for (int i = 0; i < (int) embd_inp.size(); i++) {
  831. fprintf(stderr, "%6d -> '%s'\n", embd_inp[i], vocab.id_to_token.at(embd_inp[i]).tok.c_str());
  832. }
  833. fprintf(stderr, "\n");
  834. if (params.interactive) {
  835. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  836. struct sigaction sigint_action;
  837. sigint_action.sa_handler = sigint_handler;
  838. sigemptyset (&sigint_action.sa_mask);
  839. sigint_action.sa_flags = 0;
  840. sigaction(SIGINT, &sigint_action, NULL);
  841. #elif defined (_WIN32)
  842. signal(SIGINT, sigint_handler);
  843. #endif
  844. fprintf(stderr, "%s: interactive mode on.\n", __func__);
  845. if(params.antiprompt.size()) {
  846. for (auto antiprompt : params.antiprompt) {
  847. fprintf(stderr, "Reverse prompt: '%s'\n", antiprompt.c_str());
  848. }
  849. }
  850. }
  851. fprintf(stderr, "sampling parameters: temp = %f, top_k = %d, top_p = %f, repeat_last_n = %i, repeat_penalty = %f\n", params.temp, params.top_k, params.top_p, params.repeat_last_n, params.repeat_penalty);
  852. fprintf(stderr, "\n\n");
  853. std::vector<llama_vocab::id> embd;
  854. int last_n_size = params.repeat_last_n;
  855. std::vector<llama_vocab::id> last_n_tokens(last_n_size);
  856. std::fill(last_n_tokens.begin(), last_n_tokens.end(), 0);
  857. if (params.interactive) {
  858. fprintf(stderr, "== Running in interactive mode. ==\n"
  859. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  860. " - Press Ctrl+C to interject at any time.\n"
  861. #endif
  862. " - Press Return to return control to LLaMa.\n"
  863. " - If you want to submit another line, end your input in '\\'.\n\n");
  864. is_interacting = true;
  865. }
  866. int input_consumed = 0;
  867. bool input_noecho = false;
  868. int remaining_tokens = params.n_predict;
  869. #if defined (_WIN32)
  870. if (params.use_color) {
  871. // Enable ANSI colors on Windows 10+
  872. unsigned long dwMode = 0;
  873. void* hConOut = GetStdHandle((unsigned long)-11); // STD_OUTPUT_HANDLE (-11)
  874. if (hConOut && hConOut != (void*)-1 && GetConsoleMode(hConOut, &dwMode) && !(dwMode & 0x4)) {
  875. SetConsoleMode(hConOut, dwMode | 0x4); // ENABLE_VIRTUAL_TERMINAL_PROCESSING (0x4)
  876. }
  877. }
  878. #endif
  879. // the first thing we will do is to output the prompt, so set color accordingly
  880. set_console_state(CONSOLE_STATE_PROMPT);
  881. while (remaining_tokens > 0 || params.interactive) {
  882. // predict
  883. if (embd.size() > 0) {
  884. const int64_t t_start_us = ggml_time_us();
  885. if (!llama_eval(model, params.n_threads, n_past, embd, logits, mem_per_token)) {
  886. fprintf(stderr, "Failed to predict\n");
  887. return 1;
  888. }
  889. t_predict_us += ggml_time_us() - t_start_us;
  890. }
  891. n_past += embd.size();
  892. embd.clear();
  893. if ((int) embd_inp.size() <= input_consumed) {
  894. // out of user input, sample next token
  895. const float top_k = params.top_k;
  896. const float top_p = params.top_p;
  897. const float temp = params.temp;
  898. const float repeat_penalty = params.repeat_penalty;
  899. const int n_vocab = model.hparams.n_vocab;
  900. llama_vocab::id id = 0;
  901. {
  902. const int64_t t_start_sample_us = ggml_time_us();
  903. if (params.ignore_eos) {
  904. // set the logit of the eos token to zero to avoid sampling it
  905. logits[logits.size() - n_vocab + EOS_TOKEN_ID] = 0;
  906. }
  907. id = llama_sample_top_p_top_k(vocab, logits.data() + (logits.size() - n_vocab), last_n_tokens, repeat_penalty, top_k, top_p, temp, rng);
  908. last_n_tokens.erase(last_n_tokens.begin());
  909. last_n_tokens.push_back(id);
  910. t_sample_us += ggml_time_us() - t_start_sample_us;
  911. }
  912. // add it to the context
  913. embd.push_back(id);
  914. // echo this to console
  915. input_noecho = false;
  916. // decrement remaining sampling budget
  917. --remaining_tokens;
  918. } else {
  919. // some user input remains from prompt or interaction, forward it to processing
  920. while ((int) embd_inp.size() > input_consumed) {
  921. embd.push_back(embd_inp[input_consumed]);
  922. last_n_tokens.erase(last_n_tokens.begin());
  923. last_n_tokens.push_back(embd_inp[input_consumed]);
  924. ++input_consumed;
  925. if ((int) embd.size() >= params.n_batch) {
  926. break;
  927. }
  928. }
  929. }
  930. // display text
  931. if (!input_noecho) {
  932. for (auto id : embd) {
  933. printf("%s", vocab.id_to_token[id].tok.c_str());
  934. }
  935. fflush(stdout);
  936. }
  937. // reset color to default if we there is no pending user input
  938. if (!input_noecho && (int)embd_inp.size() == input_consumed) {
  939. set_console_state(CONSOLE_STATE_DEFAULT);
  940. }
  941. // in interactive mode, and not currently processing queued inputs;
  942. // check if we should prompt the user for more
  943. if (params.interactive && (int) embd_inp.size() <= input_consumed) {
  944. // check for reverse prompt
  945. std::string last_output;
  946. for (auto id : last_n_tokens) {
  947. last_output += vocab.id_to_token[id].tok;
  948. }
  949. // Check if each of the reverse prompts appears at the end of the output.
  950. for (std::string antiprompt : params.antiprompt) {
  951. if (last_output.find(antiprompt.c_str(), last_output.length() - antiprompt.length(), antiprompt.length()) != std::string::npos) {
  952. is_interacting = true;
  953. break;
  954. }
  955. }
  956. if (is_interacting) {
  957. // potentially set color to indicate we are taking user input
  958. set_console_state(CONSOLE_STATE_USER_INPUT);
  959. if (params.instruct) {
  960. input_consumed = embd_inp.size();
  961. embd_inp.insert(embd_inp.end(), inp_pfx.begin(), inp_pfx.end());
  962. printf("\n> ");
  963. }
  964. std::string buffer;
  965. std::string line;
  966. bool another_line = true;
  967. do {
  968. std::getline(std::cin, line);
  969. if (line.empty() || line.back() != '\\') {
  970. another_line = false;
  971. } else {
  972. line.pop_back(); // Remove the continue character
  973. }
  974. buffer += line + '\n'; // Append the line to the result
  975. } while (another_line);
  976. // done taking input, reset color
  977. set_console_state(CONSOLE_STATE_DEFAULT);
  978. std::vector<llama_vocab::id> line_inp = ::llama_tokenize(vocab, buffer, false);
  979. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  980. if (params.instruct) {
  981. embd_inp.insert(embd_inp.end(), inp_sfx.begin(), inp_sfx.end());
  982. }
  983. remaining_tokens -= line_inp.size();
  984. input_noecho = true; // do not echo this again
  985. }
  986. is_interacting = false;
  987. }
  988. // end of text token
  989. if (embd.back() == EOS_TOKEN_ID) {
  990. if (params.interactive) {
  991. is_interacting = true;
  992. } else {
  993. fprintf(stderr, " [end of text]\n");
  994. break;
  995. }
  996. }
  997. // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
  998. if (params.interactive && remaining_tokens <= 0) {
  999. remaining_tokens = params.n_predict;
  1000. is_interacting = true;
  1001. }
  1002. }
  1003. #if defined (_WIN32)
  1004. signal(SIGINT, SIG_DFL);
  1005. #endif
  1006. // report timing
  1007. {
  1008. const int64_t t_main_end_us = ggml_time_us();
  1009. fprintf(stderr, "\n\n");
  1010. fprintf(stderr, "%s: mem per token = %8zu bytes\n", __func__, mem_per_token);
  1011. fprintf(stderr, "%s: load time = %8.2f ms\n", __func__, t_load_us/1000.0f);
  1012. fprintf(stderr, "%s: sample time = %8.2f ms\n", __func__, t_sample_us/1000.0f);
  1013. fprintf(stderr, "%s: predict time = %8.2f ms / %.2f ms per token\n", __func__, t_predict_us/1000.0f, t_predict_us/1000.0f/n_past);
  1014. fprintf(stderr, "%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us)/1000.0f);
  1015. }
  1016. ggml_free(model.ctx);
  1017. set_console_state(CONSOLE_STATE_DEFAULT);
  1018. return 0;
  1019. }