main.cpp 46 KB

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