1
0

main.cpp 17 KB

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