main.cpp 45 KB

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