main.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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.embedding = params.embedding;
  176. ctx = llama_init_from_file(params.model.c_str(), lparams);
  177. if (ctx == NULL) {
  178. fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
  179. return 1;
  180. }
  181. }
  182. // print system information
  183. {
  184. fprintf(stderr, "\n");
  185. fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
  186. params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
  187. }
  188. // determine the required inference memory per token:
  189. // TODO: better way to do that
  190. {
  191. const std::vector<llama_token> tmp = { 0, 1, 2, 3 };
  192. llama_eval(ctx, tmp.data(), tmp.size(), 0, params.n_threads);
  193. }
  194. if (params.perplexity) {
  195. perplexity(ctx, params);
  196. exit(0);
  197. }
  198. int n_past = 0;
  199. // Add a space in front of the first character to match OG llama tokenizer behavior
  200. params.prompt.insert(0, 1, ' ');
  201. // tokenize the prompt
  202. auto embd_inp = ::llama_tokenize(ctx, params.prompt, true);
  203. const int n_ctx = llama_n_ctx(ctx);
  204. params.n_predict = std::min(params.n_predict, n_ctx - (int) embd_inp.size());
  205. // prefix & suffix for instruct mode
  206. const auto inp_pfx = ::llama_tokenize(ctx, "\n\n### Instruction:\n\n", true);
  207. const auto inp_sfx = ::llama_tokenize(ctx, "\n\n### Response:\n\n", false);
  208. // in instruct mode, we inject a prefix and a suffix to each input by the user
  209. if (params.instruct) {
  210. params.interactive = true;
  211. params.antiprompt.push_back("### Instruction:\n\n");
  212. }
  213. // enable interactive mode if reverse prompt is specified
  214. if (params.antiprompt.size() != 0) {
  215. params.interactive = true;
  216. }
  217. if (params.interactive_start) {
  218. params.interactive = true;
  219. }
  220. // determine newline token
  221. auto llama_token_newline = ::llama_tokenize(ctx, "\n", false);
  222. fprintf(stderr, "\n");
  223. fprintf(stderr, "%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  224. fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  225. for (int i = 0; i < (int) embd_inp.size(); i++) {
  226. fprintf(stderr, "%6d -> '%s'\n", embd_inp[i], llama_token_to_str(ctx, embd_inp[i]));
  227. }
  228. fprintf(stderr, "\n");
  229. if (params.interactive) {
  230. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  231. struct sigaction sigint_action;
  232. sigint_action.sa_handler = sigint_handler;
  233. sigemptyset (&sigint_action.sa_mask);
  234. sigint_action.sa_flags = 0;
  235. sigaction(SIGINT, &sigint_action, NULL);
  236. #elif defined (_WIN32)
  237. signal(SIGINT, sigint_handler);
  238. #endif
  239. fprintf(stderr, "%s: interactive mode on.\n", __func__);
  240. if(params.antiprompt.size()) {
  241. for (auto antiprompt : params.antiprompt) {
  242. fprintf(stderr, "Reverse prompt: '%s'\n", antiprompt.c_str());
  243. }
  244. }
  245. }
  246. 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);
  247. fprintf(stderr, "\n\n");
  248. std::vector<llama_token> embd;
  249. int last_n_size = params.repeat_last_n;
  250. std::vector<llama_token> last_n_tokens(last_n_size);
  251. std::fill(last_n_tokens.begin(), last_n_tokens.end(), 0);
  252. if (params.interactive) {
  253. fprintf(stderr, "== Running in interactive mode. ==\n"
  254. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  255. " - Press Ctrl+C to interject at any time.\n"
  256. #endif
  257. " - Press Return to return control to LLaMa.\n"
  258. " - If you want to submit another line, end your input in '\\'.\n\n");
  259. is_interacting = params.interactive_start || params.instruct;
  260. }
  261. int input_consumed = 0;
  262. bool input_noecho = false;
  263. int remaining_tokens = params.n_predict;
  264. #if defined (_WIN32)
  265. if (params.use_color) {
  266. // Enable ANSI colors on Windows 10+
  267. unsigned long dwMode = 0;
  268. void* hConOut = GetStdHandle((unsigned long)-11); // STD_OUTPUT_HANDLE (-11)
  269. if (hConOut && hConOut != (void*)-1 && GetConsoleMode(hConOut, &dwMode) && !(dwMode & 0x4)) {
  270. SetConsoleMode(hConOut, dwMode | 0x4); // ENABLE_VIRTUAL_TERMINAL_PROCESSING (0x4)
  271. }
  272. }
  273. #endif
  274. // the first thing we will do is to output the prompt, so set color accordingly
  275. set_console_state(CONSOLE_STATE_PROMPT);
  276. if (params.embedding){
  277. embd = embd_inp;
  278. if (embd.size() > 0) {
  279. if (llama_eval(ctx, embd.data(), embd.size(), n_past, params.n_threads)) {
  280. fprintf(stderr, "%s : failed to eval\n", __func__);
  281. return 1;
  282. }
  283. }
  284. const auto embeddings = llama_get_embeddings(ctx);
  285. // TODO: print / use the embeddings
  286. if (params.use_color) {
  287. printf(ANSI_COLOR_RESET);
  288. }
  289. return 0;
  290. }
  291. while (remaining_tokens > 0 || params.interactive) {
  292. // predict
  293. if (embd.size() > 0) {
  294. if (llama_eval(ctx, embd.data(), embd.size(), n_past, params.n_threads)) {
  295. fprintf(stderr, "%s : failed to eval\n", __func__);
  296. return 1;
  297. }
  298. }
  299. n_past += embd.size();
  300. embd.clear();
  301. if ((int) embd_inp.size() <= input_consumed) {
  302. // out of user input, sample next token
  303. const float top_k = params.top_k;
  304. const float top_p = params.top_p;
  305. const float temp = params.temp;
  306. const float repeat_penalty = params.repeat_penalty;
  307. llama_token id = 0;
  308. {
  309. auto logits = llama_get_logits(ctx);
  310. if (params.ignore_eos) {
  311. // set the logit of the eos token to zero to avoid sampling it
  312. //logits[logits.size() - n_vocab + EOS_TOKEN_ID] = 0;
  313. // TODO: this does not work of params.logits_all == true
  314. assert(params.perplexity == false);
  315. logits[llama_token_eos()] = 0;
  316. }
  317. id = llama_sample_top_p_top_k(ctx, last_n_tokens.data(), last_n_tokens.size(), top_k, top_p, temp, repeat_penalty);
  318. last_n_tokens.erase(last_n_tokens.begin());
  319. last_n_tokens.push_back(id);
  320. }
  321. // replace end of text token with newline token when in interactive mode
  322. if (id == llama_token_eos() && params.interactive) {
  323. id = llama_token_newline.front();
  324. if (params.antiprompt.size() != 0) {
  325. // tokenize and inject first reverse prompt
  326. const auto first_antiprompt = ::llama_tokenize(ctx, params.antiprompt.front(), false);
  327. embd_inp.insert(embd_inp.end(), first_antiprompt.begin(), first_antiprompt.end());
  328. }
  329. }
  330. // add it to the context
  331. embd.push_back(id);
  332. // echo this to console
  333. input_noecho = false;
  334. // decrement remaining sampling budget
  335. --remaining_tokens;
  336. } else {
  337. // some user input remains from prompt or interaction, forward it to processing
  338. while ((int) embd_inp.size() > input_consumed) {
  339. embd.push_back(embd_inp[input_consumed]);
  340. last_n_tokens.erase(last_n_tokens.begin());
  341. last_n_tokens.push_back(embd_inp[input_consumed]);
  342. ++input_consumed;
  343. if ((int) embd.size() >= params.n_batch) {
  344. break;
  345. }
  346. }
  347. }
  348. // display text
  349. if (!input_noecho) {
  350. for (auto id : embd) {
  351. printf("%s", llama_token_to_str(ctx, id));
  352. }
  353. fflush(stdout);
  354. }
  355. // reset color to default if we there is no pending user input
  356. if (!input_noecho && (int)embd_inp.size() == input_consumed) {
  357. set_console_state(CONSOLE_STATE_DEFAULT);
  358. }
  359. // in interactive mode, and not currently processing queued inputs;
  360. // check if we should prompt the user for more
  361. if (params.interactive && (int) embd_inp.size() <= input_consumed) {
  362. // check for reverse prompt
  363. std::string last_output;
  364. for (auto id : last_n_tokens) {
  365. last_output += llama_token_to_str(ctx, id);
  366. }
  367. // Check if each of the reverse prompts appears at the end of the output.
  368. for (std::string antiprompt : params.antiprompt) {
  369. if (last_output.find(antiprompt.c_str(), last_output.length() - antiprompt.length(), antiprompt.length()) != std::string::npos) {
  370. is_interacting = true;
  371. break;
  372. }
  373. }
  374. if (is_interacting) {
  375. // potentially set color to indicate we are taking user input
  376. set_console_state(CONSOLE_STATE_USER_INPUT);
  377. if (params.instruct) {
  378. input_consumed = embd_inp.size();
  379. embd_inp.insert(embd_inp.end(), inp_pfx.begin(), inp_pfx.end());
  380. printf("\n> ");
  381. }
  382. std::string buffer;
  383. std::string line;
  384. bool another_line = true;
  385. do {
  386. std::getline(std::cin, line);
  387. if (line.empty() || line.back() != '\\') {
  388. another_line = false;
  389. } else {
  390. line.pop_back(); // Remove the continue character
  391. }
  392. buffer += line + '\n'; // Append the line to the result
  393. } while (another_line);
  394. // done taking input, reset color
  395. set_console_state(CONSOLE_STATE_DEFAULT);
  396. auto line_inp = ::llama_tokenize(ctx, buffer, false);
  397. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  398. if (params.instruct) {
  399. embd_inp.insert(embd_inp.end(), inp_sfx.begin(), inp_sfx.end());
  400. }
  401. remaining_tokens -= line_inp.size();
  402. input_noecho = true; // do not echo this again
  403. }
  404. is_interacting = false;
  405. }
  406. // end of text token
  407. if (embd.back() == llama_token_eos()) {
  408. fprintf(stderr, " [end of text]\n");
  409. break;
  410. }
  411. // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
  412. if (params.interactive && remaining_tokens <= 0) {
  413. remaining_tokens = params.n_predict;
  414. is_interacting = true;
  415. }
  416. }
  417. #if defined (_WIN32)
  418. signal(SIGINT, SIG_DFL);
  419. #endif
  420. llama_print_timings(ctx);
  421. llama_free(ctx);
  422. set_console_state(CONSOLE_STATE_DEFAULT);
  423. return 0;
  424. }