main.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. #include "utils.h"
  2. #include "ggml.h"
  3. #include "llama.h"
  4. #include <cassert>
  5. #include <cinttypes>
  6. #include <cmath>
  7. #include <cstdio>
  8. #include <cstring>
  9. #include <fstream>
  10. #include <iostream>
  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. std::vector<double> softmax(const std::vector<float>& logits) {
  61. std::vector<double> probs(logits.size());
  62. float max_logit = logits[0];
  63. for (float v : logits) max_logit = std::max(max_logit, v);
  64. double sum_exp = 0.0;
  65. for (size_t i = 0; i < logits.size(); i++) {
  66. // Subtract the maximum logit value from the current logit value for numerical stability
  67. float logit = logits[i] - max_logit;
  68. double exp_logit = std::exp(logit);
  69. sum_exp += exp_logit;
  70. probs[i] = exp_logit;
  71. }
  72. for (size_t i = 0; i < probs.size(); i++) probs[i] /= sum_exp;
  73. return probs;
  74. }
  75. void perplexity(llama_context * ctx, const gpt_params & params) {
  76. // Download: https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-raw-v1.zip?ref=salesforce-research
  77. // Run `./main --perplexity -m models/7B/ggml-model-q4_0.bin -f wiki.test.raw`
  78. // Output: `perplexity: 13.5106 [114/114]`
  79. auto tokens = ::llama_tokenize(ctx, params.prompt, true);
  80. int count = 0;
  81. double nll = 0.0;
  82. int seq_count = tokens.size() / params.n_ctx;
  83. fprintf(stderr, "%s : calculating perplexity over %d chunks\n", __func__, seq_count);
  84. for (int i = 0; i < seq_count; ++i) {
  85. int start = i * params.n_ctx;
  86. int end = start + params.n_ctx - 1;
  87. std::vector<llama_token> embd(tokens.begin() + start, tokens.begin() + end);
  88. auto start_t = std::chrono::high_resolution_clock::now();
  89. if (llama_eval(ctx, embd.data(), embd.size(), 0, params.n_threads)) {
  90. fprintf(stderr, "%s : failed to eval\n", __func__);
  91. return;
  92. }
  93. auto end_t = std::chrono::high_resolution_clock::now();
  94. if (i == 0) {
  95. double seconds = std::chrono::duration<double>(end_t - start_t).count();
  96. printf("%.2f seconds per pass - ETA %.2f hours\n", seconds, (seconds * seq_count) / (60.0*60.0));
  97. }
  98. // We get the logits for all the tokens in the context window (params.n_ctx)
  99. // from llama_eval above. Now, based on https://huggingface.co/docs/transformers/perplexity,
  100. // calculate the perplexity over the last half the window (so the model always has
  101. // some context to predict the token).
  102. //
  103. // We rely on the fact that attention in the forward pass only looks at previous
  104. // tokens here, so the logits returned for each token are an accurate representation
  105. // of what the model would have predicted at that point.
  106. //
  107. // Example, we have a context window of 512, we will compute perplexity for each of the
  108. // last 256 tokens. Then, we split the input up into context window size chunks to
  109. // process the entire prompt.
  110. auto logits = llama_get_logits(ctx);
  111. for (int j = params.n_ctx / 2; j < params.n_ctx - 1; ++j) {
  112. // Calculate probability of next token, given the previous ones.
  113. int n_vocab = llama_n_vocab(ctx);
  114. std::vector<float> tok_logits(
  115. logits + j * n_vocab,
  116. logits + (j + 1) * n_vocab);
  117. double prob = softmax(tok_logits)[tokens[start + j + 1]];
  118. nll += -std::log(prob);
  119. ++count;
  120. }
  121. // perplexity is e^(average negative log-likelihood)
  122. printf("[%d]%.4lf,", i + 1, std::exp(nll / count));
  123. fflush(stdout);
  124. }
  125. printf("\n");
  126. }
  127. static bool is_interacting = false;
  128. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  129. void sigint_handler(int signo) {
  130. set_console_state(CONSOLE_STATE_DEFAULT);
  131. printf("\n"); // this also force flush stdout.
  132. if (signo == SIGINT) {
  133. if (!is_interacting) {
  134. is_interacting=true;
  135. } else {
  136. _exit(130);
  137. }
  138. }
  139. }
  140. #endif
  141. int main(int argc, char ** argv) {
  142. // has to be called once at the start of the program to init ggml stuff
  143. ggml_time_init();
  144. gpt_params params;
  145. params.model = "models/llama-7B/ggml-model.bin";
  146. if (gpt_params_parse(argc, argv, params) == false) {
  147. return 1;
  148. }
  149. if (params.n_ctx > 2048) {
  150. fprintf(stderr, "%s: warning: model does not support context sizes greater than 2048 tokens (%d specified);"
  151. "expect poor results\n", __func__, params.n_ctx);
  152. }
  153. if (params.seed <= 0) {
  154. params.seed = time(NULL);
  155. }
  156. fprintf(stderr, "%s: seed = %d\n", __func__, params.seed);
  157. std::mt19937 rng(params.seed);
  158. if (params.random_prompt) {
  159. params.prompt = gpt_random_prompt(rng);
  160. }
  161. // save choice to use color for later
  162. // (note for later: this is a slightly awkward choice)
  163. con_use_color = params.use_color;
  164. // params.prompt = R"(// this function checks if the number n is prime
  165. //bool is_prime(int n) {)";
  166. llama_context * ctx;
  167. // load the model
  168. {
  169. auto lparams = llama_context_default_params();
  170. lparams.n_ctx = params.n_ctx;
  171. lparams.n_parts = params.n_parts;
  172. lparams.seed = params.seed;
  173. lparams.f16_kv = params.memory_f16;
  174. lparams.logits_all = params.perplexity;
  175. lparams.use_mlock = params.use_mlock;
  176. lparams.embedding = params.embedding;
  177. ctx = llama_init_from_file(params.model.c_str(), lparams);
  178. if (ctx == NULL) {
  179. fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
  180. return 1;
  181. }
  182. }
  183. // print system information
  184. {
  185. fprintf(stderr, "\n");
  186. fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
  187. params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
  188. }
  189. // determine the maximum memory usage needed to do inference for the given n_batch and n_predict parameters
  190. // uncomment the "used_mem" line in llama.cpp to see the results
  191. if (params.mem_test) {
  192. {
  193. const std::vector<llama_token> tmp(params.n_batch, 0);
  194. llama_eval(ctx, tmp.data(), tmp.size(), 0, params.n_threads);
  195. }
  196. {
  197. const std::vector<llama_token> tmp = { 0, };
  198. llama_eval(ctx, tmp.data(), tmp.size(), params.n_predict - 1, params.n_threads);
  199. }
  200. llama_print_timings(ctx);
  201. llama_free(ctx);
  202. return 0;
  203. }
  204. if (params.perplexity) {
  205. perplexity(ctx, params);
  206. exit(0);
  207. }
  208. int n_past = 0;
  209. // Add a space in front of the first character to match OG llama tokenizer behavior
  210. params.prompt.insert(0, 1, ' ');
  211. // tokenize the prompt
  212. auto embd_inp = ::llama_tokenize(ctx, params.prompt, true);
  213. const int n_ctx = llama_n_ctx(ctx);
  214. params.n_predict = std::min(params.n_predict, n_ctx - (int) embd_inp.size());
  215. // prefix & suffix for instruct mode
  216. const auto inp_pfx = ::llama_tokenize(ctx, "\n\n### Instruction:\n\n", true);
  217. const auto inp_sfx = ::llama_tokenize(ctx, "\n\n### Response:\n\n", false);
  218. // in instruct mode, we inject a prefix and a suffix to each input by the user
  219. if (params.instruct) {
  220. params.interactive = true;
  221. params.antiprompt.push_back("### Instruction:\n\n");
  222. }
  223. // enable interactive mode if reverse prompt is specified
  224. if (params.antiprompt.size() != 0) {
  225. params.interactive = true;
  226. }
  227. if (params.interactive_start) {
  228. params.interactive = true;
  229. }
  230. // determine newline token
  231. auto llama_token_newline = ::llama_tokenize(ctx, "\n", false);
  232. fprintf(stderr, "\n");
  233. fprintf(stderr, "%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  234. fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  235. for (int i = 0; i < (int) embd_inp.size(); i++) {
  236. fprintf(stderr, "%6d -> '%s'\n", embd_inp[i], llama_token_to_str(ctx, embd_inp[i]));
  237. }
  238. fprintf(stderr, "\n");
  239. if (params.interactive) {
  240. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  241. struct sigaction sigint_action;
  242. sigint_action.sa_handler = sigint_handler;
  243. sigemptyset (&sigint_action.sa_mask);
  244. sigint_action.sa_flags = 0;
  245. sigaction(SIGINT, &sigint_action, NULL);
  246. #elif defined (_WIN32)
  247. signal(SIGINT, sigint_handler);
  248. #endif
  249. fprintf(stderr, "%s: interactive mode on.\n", __func__);
  250. if(params.antiprompt.size()) {
  251. for (auto antiprompt : params.antiprompt) {
  252. fprintf(stderr, "Reverse prompt: '%s'\n", antiprompt.c_str());
  253. }
  254. }
  255. }
  256. 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);
  257. fprintf(stderr, "\n\n");
  258. std::vector<llama_token> embd;
  259. int last_n_size = params.repeat_last_n;
  260. std::vector<llama_token> last_n_tokens(last_n_size);
  261. std::fill(last_n_tokens.begin(), last_n_tokens.end(), 0);
  262. if (params.interactive) {
  263. fprintf(stderr, "== Running in interactive mode. ==\n"
  264. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  265. " - Press Ctrl+C to interject at any time.\n"
  266. #endif
  267. " - Press Return to return control to LLaMa.\n"
  268. " - If you want to submit another line, end your input in '\\'.\n\n");
  269. is_interacting = params.interactive_start || params.instruct;
  270. }
  271. int input_consumed = 0;
  272. bool input_noecho = false;
  273. int remaining_tokens = params.n_predict;
  274. #if defined (_WIN32)
  275. if (params.use_color) {
  276. // Enable ANSI colors on Windows 10+
  277. unsigned long dwMode = 0;
  278. void* hConOut = GetStdHandle((unsigned long)-11); // STD_OUTPUT_HANDLE (-11)
  279. if (hConOut && hConOut != (void*)-1 && GetConsoleMode(hConOut, &dwMode) && !(dwMode & 0x4)) {
  280. SetConsoleMode(hConOut, dwMode | 0x4); // ENABLE_VIRTUAL_TERMINAL_PROCESSING (0x4)
  281. }
  282. }
  283. #endif
  284. // the first thing we will do is to output the prompt, so set color accordingly
  285. set_console_state(CONSOLE_STATE_PROMPT);
  286. if (params.embedding){
  287. embd = embd_inp;
  288. if (embd.size() > 0) {
  289. if (llama_eval(ctx, embd.data(), embd.size(), n_past, params.n_threads)) {
  290. fprintf(stderr, "%s : failed to eval\n", __func__);
  291. return 1;
  292. }
  293. }
  294. const auto embeddings = llama_get_embeddings(ctx);
  295. // TODO: print / use the embeddings
  296. if (params.use_color) {
  297. printf(ANSI_COLOR_RESET);
  298. }
  299. return 0;
  300. }
  301. while (remaining_tokens > 0 || params.interactive) {
  302. // predict
  303. if (embd.size() > 0) {
  304. if (llama_eval(ctx, embd.data(), embd.size(), n_past, params.n_threads)) {
  305. fprintf(stderr, "%s : failed to eval\n", __func__);
  306. return 1;
  307. }
  308. }
  309. n_past += embd.size();
  310. embd.clear();
  311. if ((int) embd_inp.size() <= input_consumed && !is_interacting) {
  312. // out of user input, sample next token
  313. const float top_k = params.top_k;
  314. const float top_p = params.top_p;
  315. const float temp = params.temp;
  316. const float repeat_penalty = params.repeat_penalty;
  317. llama_token id = 0;
  318. {
  319. auto logits = llama_get_logits(ctx);
  320. if (params.ignore_eos) {
  321. // set the logit of the eos token to zero to avoid sampling it
  322. //logits[logits.size() - n_vocab + EOS_TOKEN_ID] = 0;
  323. // TODO: this does not work of params.logits_all == true
  324. assert(params.perplexity == false);
  325. logits[llama_token_eos()] = 0;
  326. }
  327. id = llama_sample_top_p_top_k(ctx, last_n_tokens.data(), last_n_tokens.size(), top_k, top_p, temp, repeat_penalty);
  328. last_n_tokens.erase(last_n_tokens.begin());
  329. last_n_tokens.push_back(id);
  330. }
  331. // replace end of text token with newline token when in interactive mode
  332. if (id == llama_token_eos() && params.interactive && !params.instruct) {
  333. id = llama_token_newline.front();
  334. if (params.antiprompt.size() != 0) {
  335. // tokenize and inject first reverse prompt
  336. const auto first_antiprompt = ::llama_tokenize(ctx, params.antiprompt.front(), false);
  337. embd_inp.insert(embd_inp.end(), first_antiprompt.begin(), first_antiprompt.end());
  338. }
  339. }
  340. // add it to the context
  341. embd.push_back(id);
  342. // echo this to console
  343. input_noecho = false;
  344. // decrement remaining sampling budget
  345. --remaining_tokens;
  346. } else {
  347. // some user input remains from prompt or interaction, forward it to processing
  348. while ((int) embd_inp.size() > input_consumed) {
  349. embd.push_back(embd_inp[input_consumed]);
  350. last_n_tokens.erase(last_n_tokens.begin());
  351. last_n_tokens.push_back(embd_inp[input_consumed]);
  352. ++input_consumed;
  353. if ((int) embd.size() >= params.n_batch) {
  354. break;
  355. }
  356. }
  357. }
  358. // display text
  359. if (!input_noecho) {
  360. for (auto id : embd) {
  361. printf("%s", llama_token_to_str(ctx, id));
  362. }
  363. fflush(stdout);
  364. }
  365. // reset color to default if we there is no pending user input
  366. if (!input_noecho && (int)embd_inp.size() == input_consumed) {
  367. set_console_state(CONSOLE_STATE_DEFAULT);
  368. }
  369. // in interactive mode, and not currently processing queued inputs;
  370. // check if we should prompt the user for more
  371. if (params.interactive && (int) embd_inp.size() <= input_consumed) {
  372. // check for reverse prompt
  373. std::string last_output;
  374. for (auto id : last_n_tokens) {
  375. last_output += llama_token_to_str(ctx, id);
  376. }
  377. // Check if each of the reverse prompts appears at the end of the output.
  378. for (std::string & antiprompt : params.antiprompt) {
  379. if (last_output.find(antiprompt.c_str(), last_output.length() - antiprompt.length(), antiprompt.length()) != std::string::npos) {
  380. is_interacting = true;
  381. set_console_state(CONSOLE_STATE_USER_INPUT);
  382. fflush(stdout);
  383. break;
  384. }
  385. }
  386. if (n_past > 0 && is_interacting) {
  387. // potentially set color to indicate we are taking user input
  388. set_console_state(CONSOLE_STATE_USER_INPUT);
  389. if (params.instruct) {
  390. input_consumed = embd_inp.size();
  391. embd_inp.insert(embd_inp.end(), inp_pfx.begin(), inp_pfx.end());
  392. printf("\n> ");
  393. }
  394. std::string buffer;
  395. std::string line;
  396. bool another_line = true;
  397. do {
  398. std::getline(std::cin, line);
  399. if (line.empty() || line.back() != '\\') {
  400. another_line = false;
  401. } else {
  402. line.pop_back(); // Remove the continue character
  403. }
  404. buffer += line + '\n'; // Append the line to the result
  405. } while (another_line);
  406. // done taking input, reset color
  407. set_console_state(CONSOLE_STATE_DEFAULT);
  408. auto line_inp = ::llama_tokenize(ctx, buffer, false);
  409. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  410. if (params.instruct) {
  411. embd_inp.insert(embd_inp.end(), inp_sfx.begin(), inp_sfx.end());
  412. }
  413. remaining_tokens -= line_inp.size();
  414. input_noecho = true; // do not echo this again
  415. }
  416. if (n_past > 0) {
  417. is_interacting = false;
  418. }
  419. }
  420. // end of text token
  421. if (embd.back() == llama_token_eos()) {
  422. if (params.instruct) {
  423. is_interacting = true;
  424. } else {
  425. fprintf(stderr, " [end of text]\n");
  426. break;
  427. }
  428. }
  429. // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
  430. if (params.interactive && remaining_tokens <= 0) {
  431. remaining_tokens = params.n_predict;
  432. is_interacting = true;
  433. }
  434. }
  435. #if defined (_WIN32)
  436. signal(SIGINT, SIG_DFL);
  437. #endif
  438. llama_print_timings(ctx);
  439. llama_free(ctx);
  440. set_console_state(CONSOLE_STATE_DEFAULT);
  441. return 0;
  442. }