main.cpp 45 KB

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