main.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. // Defines sigaction on msys:
  2. #ifndef _GNU_SOURCE
  3. #define _GNU_SOURCE
  4. #endif
  5. #include "common.h"
  6. #include "llama.h"
  7. #include <cassert>
  8. #include <cinttypes>
  9. #include <cmath>
  10. #include <cstdio>
  11. #include <cstring>
  12. #include <ctime>
  13. #include <fstream>
  14. #include <iostream>
  15. #include <string>
  16. #include <vector>
  17. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  18. #include <signal.h>
  19. #include <unistd.h>
  20. #elif defined (_WIN32)
  21. #include <signal.h>
  22. #endif
  23. static console_state con_st;
  24. static llama_context ** g_ctx;
  25. static bool is_interacting = false;
  26. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  27. void sigint_handler(int signo) {
  28. set_console_color(con_st, CONSOLE_COLOR_DEFAULT);
  29. printf("\n"); // this also force flush stdout.
  30. if (signo == SIGINT) {
  31. if (!is_interacting) {
  32. is_interacting=true;
  33. } else {
  34. llama_print_timings(*g_ctx);
  35. _exit(130);
  36. }
  37. }
  38. }
  39. #endif
  40. int main(int argc, char ** argv) {
  41. gpt_params params;
  42. params.model = "models/llama-7B/ggml-model.bin";
  43. if (gpt_params_parse(argc, argv, params) == false) {
  44. return 1;
  45. }
  46. // save choice to use color for later
  47. // (note for later: this is a slightly awkward choice)
  48. con_st.use_color = params.use_color;
  49. #if defined (_WIN32)
  50. win32_console_init(params.use_color);
  51. #endif
  52. if (params.perplexity) {
  53. printf("\n************\n");
  54. printf("%s: please use the 'perplexity' tool for perplexity calculations\n", __func__);
  55. printf("************\n\n");
  56. return 0;
  57. }
  58. if (params.embedding) {
  59. printf("\n************\n");
  60. printf("%s: please use the 'embedding' tool for embedding calculations\n", __func__);
  61. printf("************\n\n");
  62. return 0;
  63. }
  64. if (params.n_ctx > 2048) {
  65. fprintf(stderr, "%s: warning: model does not support context sizes greater than 2048 tokens (%d specified);"
  66. "expect poor results\n", __func__, params.n_ctx);
  67. }
  68. if (params.seed <= 0) {
  69. params.seed = time(NULL);
  70. }
  71. fprintf(stderr, "%s: seed = %d\n", __func__, params.seed);
  72. std::mt19937 rng(params.seed);
  73. if (params.random_prompt) {
  74. params.prompt = gpt_random_prompt(rng);
  75. }
  76. // params.prompt = R"(// this function checks if the number n is prime
  77. //bool is_prime(int n) {)";
  78. llama_context * ctx;
  79. g_ctx = &ctx;
  80. // load the model
  81. {
  82. auto lparams = llama_context_default_params();
  83. lparams.n_ctx = params.n_ctx;
  84. lparams.n_parts = params.n_parts;
  85. lparams.seed = params.seed;
  86. lparams.f16_kv = params.memory_f16;
  87. lparams.use_mmap = params.use_mmap;
  88. lparams.use_mlock = params.use_mlock;
  89. ctx = llama_init_from_file(params.model.c_str(), lparams);
  90. if (ctx == NULL) {
  91. fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
  92. return 1;
  93. }
  94. }
  95. if (!params.lora_adapter.empty()) {
  96. int err = llama_apply_lora_from_file(ctx,
  97. params.lora_adapter.c_str(),
  98. params.lora_base.empty() ? NULL : params.lora_base.c_str(),
  99. params.n_threads);
  100. if (err != 0) {
  101. fprintf(stderr, "%s: error: failed to apply lora adapter\n", __func__);
  102. return 1;
  103. }
  104. }
  105. // print system information
  106. {
  107. fprintf(stderr, "\n");
  108. fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
  109. params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
  110. }
  111. // determine the maximum memory usage needed to do inference for the given n_batch and n_predict parameters
  112. // uncomment the "used_mem" line in llama.cpp to see the results
  113. if (params.mem_test) {
  114. {
  115. const std::vector<llama_token> tmp(params.n_batch, 0);
  116. llama_eval(ctx, tmp.data(), tmp.size(), 0, params.n_threads);
  117. }
  118. {
  119. const std::vector<llama_token> tmp = { 0, };
  120. llama_eval(ctx, tmp.data(), tmp.size(), params.n_predict - 1, params.n_threads);
  121. }
  122. llama_print_timings(ctx);
  123. llama_free(ctx);
  124. return 0;
  125. }
  126. // Add a space in front of the first character to match OG llama tokenizer behavior
  127. params.prompt.insert(0, 1, ' ');
  128. std::string path_session = params.path_session;
  129. std::vector<llama_token> session_tokens;
  130. if (!path_session.empty()) {
  131. fprintf(stderr, "%s: attempting to load saved session from %s..\n", __func__, path_session.c_str());
  132. // REVIEW - fopen to check for existing session
  133. FILE * fp = std::fopen(path_session.c_str(), "rb");
  134. if (fp != NULL) {
  135. std::fclose(fp);
  136. session_tokens.resize(params.n_ctx);
  137. size_t n_token_count_out = 0;
  138. const size_t n_session_bytes = llama_load_session_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.capacity(), &n_token_count_out);
  139. session_tokens.resize(n_token_count_out);
  140. if (n_session_bytes > 0) {
  141. fprintf(stderr, "%s: loaded %zu bytes of session data!\n", __func__, n_session_bytes);
  142. } else {
  143. fprintf(stderr, "%s: could not load session file, will recreate\n", __func__);
  144. }
  145. } else {
  146. fprintf(stderr, "%s: session file does not exist, will create\n", __func__);
  147. }
  148. }
  149. // tokenize the prompt
  150. auto embd_inp = ::llama_tokenize(ctx, params.prompt, true);
  151. const int n_ctx = llama_n_ctx(ctx);
  152. if ((int) embd_inp.size() > n_ctx - 4) {
  153. fprintf(stderr, "%s: error: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4);
  154. return 1;
  155. }
  156. // debug message about similarity of saved session, if applicable
  157. size_t n_matching_session_tokens = 0;
  158. if (session_tokens.size()) {
  159. for (llama_token id : session_tokens) {
  160. if (n_matching_session_tokens >= embd_inp.size() || id != embd_inp[n_matching_session_tokens]) {
  161. break;
  162. }
  163. n_matching_session_tokens++;
  164. }
  165. if (n_matching_session_tokens >= embd_inp.size()) {
  166. fprintf(stderr, "%s: session file has exact match for prompt!\n", __func__);
  167. } else if (n_matching_session_tokens < (embd_inp.size() / 2)) {
  168. fprintf(stderr, "%s: warning: session file has low similarity to prompt (%zu / %zu tokens); will mostly be reevaluated\n",
  169. __func__, n_matching_session_tokens, embd_inp.size());
  170. } else {
  171. fprintf(stderr, "%s: session file matches %zu / %zu tokens of prompt\n",
  172. __func__, n_matching_session_tokens, embd_inp.size());
  173. }
  174. }
  175. // number of tokens to keep when resetting context
  176. if (params.n_keep < 0 || params.n_keep > (int)embd_inp.size() || params.instruct) {
  177. params.n_keep = (int)embd_inp.size();
  178. }
  179. // prefix & suffix for instruct mode
  180. const auto inp_pfx = ::llama_tokenize(ctx, "\n\n### Instruction:\n\n", true);
  181. const auto inp_sfx = ::llama_tokenize(ctx, "\n\n### Response:\n\n", false);
  182. // in instruct mode, we inject a prefix and a suffix to each input by the user
  183. if (params.instruct) {
  184. params.interactive_first = true;
  185. params.antiprompt.push_back("### Instruction:\n\n");
  186. }
  187. // enable interactive mode if reverse prompt or interactive start is specified
  188. if (params.antiprompt.size() != 0 || params.interactive_first) {
  189. params.interactive = true;
  190. }
  191. // determine newline token
  192. auto llama_token_newline = ::llama_tokenize(ctx, "\n", false);
  193. if (params.verbose_prompt) {
  194. fprintf(stderr, "\n");
  195. fprintf(stderr, "%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  196. fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  197. for (int i = 0; i < (int) embd_inp.size(); i++) {
  198. fprintf(stderr, "%6d -> '%s'\n", embd_inp[i], llama_token_to_str(ctx, embd_inp[i]));
  199. }
  200. if (params.n_keep > 0) {
  201. fprintf(stderr, "%s: static prompt based on n_keep: '", __func__);
  202. for (int i = 0; i < params.n_keep; i++) {
  203. fprintf(stderr, "%s", llama_token_to_str(ctx, embd_inp[i]));
  204. }
  205. fprintf(stderr, "'\n");
  206. }
  207. fprintf(stderr, "\n");
  208. }
  209. if (params.interactive) {
  210. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  211. struct sigaction sigint_action;
  212. sigint_action.sa_handler = sigint_handler;
  213. sigemptyset (&sigint_action.sa_mask);
  214. sigint_action.sa_flags = 0;
  215. sigaction(SIGINT, &sigint_action, NULL);
  216. #elif defined (_WIN32)
  217. signal(SIGINT, sigint_handler);
  218. #endif
  219. fprintf(stderr, "%s: interactive mode on.\n", __func__);
  220. if (params.antiprompt.size()) {
  221. for (auto antiprompt : params.antiprompt) {
  222. fprintf(stderr, "Reverse prompt: '%s'\n", antiprompt.c_str());
  223. }
  224. }
  225. if (!params.input_prefix.empty()) {
  226. fprintf(stderr, "Input prefix: '%s'\n", params.input_prefix.c_str());
  227. }
  228. }
  229. fprintf(stderr, "sampling: temp = %f, top_k = %d, top_p = %f, repeat_last_n = %i, repeat_penalty = %f\n",
  230. params.temp, params.top_k, params.top_p, params.repeat_last_n, params.repeat_penalty);
  231. fprintf(stderr, "generate: n_ctx = %d, n_batch = %d, n_predict = %d, n_keep = %d\n", n_ctx, params.n_batch, params.n_predict, params.n_keep);
  232. fprintf(stderr, "\n\n");
  233. // TODO: replace with ring-buffer
  234. std::vector<llama_token> last_n_tokens(n_ctx);
  235. std::fill(last_n_tokens.begin(), last_n_tokens.end(), 0);
  236. if (params.interactive) {
  237. fprintf(stderr, "== Running in interactive mode. ==\n"
  238. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  239. " - Press Ctrl+C to interject at any time.\n"
  240. #endif
  241. " - Press Return to return control to LLaMa.\n"
  242. " - If you want to submit another line, end your input in '\\'.\n\n");
  243. is_interacting = params.interactive_first;
  244. }
  245. bool is_antiprompt = false;
  246. bool input_noecho = false;
  247. // HACK - because session saving incurs a non-negligible delay, for now skip re-saving session
  248. // if we loaded a session with at least 75% similarity. It's currently just used to speed up the
  249. // initial prompt so it doesn't need to be an exact match.
  250. bool need_to_save_session = !path_session.empty() && n_matching_session_tokens < (embd_inp.size() * 3 / 4);
  251. int n_past = 0;
  252. int n_remain = params.n_predict;
  253. int n_consumed = 0;
  254. int n_session_consumed = 0;
  255. // the first thing we will do is to output the prompt, so set color accordingly
  256. set_console_color(con_st, CONSOLE_COLOR_PROMPT);
  257. std::vector<llama_token> embd;
  258. while (n_remain != 0 || params.interactive) {
  259. // predict
  260. if (embd.size() > 0) {
  261. // infinite text generation via context swapping
  262. // if we run out of context:
  263. // - take the n_keep first tokens from the original prompt (via n_past)
  264. // - take half of the last (n_ctx - n_keep) tokens and recompute the logits in batches
  265. if (n_past + (int) embd.size() > n_ctx) {
  266. const int n_left = n_past - params.n_keep;
  267. n_past = params.n_keep;
  268. // insert n_left/2 tokens at the start of embd from last_n_tokens
  269. embd.insert(embd.begin(), last_n_tokens.begin() + n_ctx - n_left/2 - embd.size(), last_n_tokens.end() - embd.size());
  270. // REVIEW - stop saving session if we run out of context
  271. path_session = "";
  272. //printf("\n---\n");
  273. //printf("resetting: '");
  274. //for (int i = 0; i < (int) embd.size(); i++) {
  275. // printf("%s", llama_token_to_str(ctx, embd[i]));
  276. //}
  277. //printf("'\n");
  278. //printf("\n---\n");
  279. }
  280. // try to reuse a matching prefix from the loaded session instead of re-eval (via n_past)
  281. // REVIEW
  282. if (n_session_consumed < (int) session_tokens.size()) {
  283. size_t i = 0;
  284. for ( ; i < embd.size(); i++) {
  285. if (embd[i] != session_tokens[n_session_consumed]) {
  286. session_tokens.resize(n_session_consumed);
  287. break;
  288. }
  289. n_past++;
  290. n_session_consumed++;
  291. if (n_session_consumed >= (int) session_tokens.size()) {
  292. break;
  293. }
  294. }
  295. if (i > 0) {
  296. embd.erase(embd.begin(), embd.begin() + i);
  297. }
  298. }
  299. // evaluate tokens in batches
  300. // embd is typically prepared beforehand to fit within a batch, but not always
  301. for (int i = 0; i < (int) embd.size(); i += params.n_batch) {
  302. int n_eval = (int) embd.size() - i;
  303. if (n_eval > params.n_batch) {
  304. n_eval = params.n_batch;
  305. }
  306. if (llama_eval(ctx, &embd[i], n_eval, n_past, params.n_threads)) {
  307. fprintf(stderr, "%s : failed to eval\n", __func__);
  308. return 1;
  309. }
  310. n_past += n_eval;
  311. }
  312. if (embd.size() > 0 && !path_session.empty()) {
  313. session_tokens.insert(session_tokens.end(), embd.begin(), embd.end());
  314. n_session_consumed = session_tokens.size();
  315. }
  316. }
  317. embd.clear();
  318. if ((int) embd_inp.size() <= n_consumed && !is_interacting) {
  319. // out of user input, sample next token
  320. const int32_t top_k = params.top_k;
  321. const float top_p = params.top_p;
  322. const float temp = params.temp;
  323. const float repeat_penalty = params.repeat_penalty;
  324. // optionally save the session on first sample (for faster prompt loading next time)
  325. if (!path_session.empty() && need_to_save_session) {
  326. need_to_save_session = false;
  327. llama_save_session_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
  328. }
  329. llama_token id = 0;
  330. {
  331. auto logits = llama_get_logits(ctx);
  332. if (params.ignore_eos) {
  333. logits[llama_token_eos()] = 0;
  334. }
  335. id = llama_sample_top_p_top_k(ctx,
  336. last_n_tokens.data() + n_ctx - params.repeat_last_n,
  337. params.repeat_last_n, top_k, top_p, temp, repeat_penalty);
  338. last_n_tokens.erase(last_n_tokens.begin());
  339. last_n_tokens.push_back(id);
  340. }
  341. // replace end of text token with newline token when in interactive mode
  342. if (id == llama_token_eos() && params.interactive && !params.instruct) {
  343. id = llama_token_newline.front();
  344. if (params.antiprompt.size() != 0) {
  345. // tokenize and inject first reverse prompt
  346. const auto first_antiprompt = ::llama_tokenize(ctx, params.antiprompt.front(), false);
  347. embd_inp.insert(embd_inp.end(), first_antiprompt.begin(), first_antiprompt.end());
  348. }
  349. }
  350. // add it to the context
  351. embd.push_back(id);
  352. // echo this to console
  353. input_noecho = false;
  354. // decrement remaining sampling budget
  355. --n_remain;
  356. } else {
  357. // some user input remains from prompt or interaction, forward it to processing
  358. while ((int) embd_inp.size() > n_consumed) {
  359. embd.push_back(embd_inp[n_consumed]);
  360. last_n_tokens.erase(last_n_tokens.begin());
  361. last_n_tokens.push_back(embd_inp[n_consumed]);
  362. ++n_consumed;
  363. if ((int) embd.size() >= params.n_batch) {
  364. break;
  365. }
  366. }
  367. }
  368. // display text
  369. if (!input_noecho) {
  370. for (auto id : embd) {
  371. printf("%s", llama_token_to_str(ctx, id));
  372. }
  373. fflush(stdout);
  374. }
  375. // reset color to default if we there is no pending user input
  376. if (!input_noecho && (int)embd_inp.size() == n_consumed) {
  377. set_console_color(con_st, CONSOLE_COLOR_DEFAULT);
  378. }
  379. // in interactive mode, and not currently processing queued inputs;
  380. // check if we should prompt the user for more
  381. if (params.interactive && (int) embd_inp.size() <= n_consumed) {
  382. // check for reverse prompt
  383. if (params.antiprompt.size()) {
  384. std::string last_output;
  385. for (auto id : last_n_tokens) {
  386. last_output += llama_token_to_str(ctx, id);
  387. }
  388. is_antiprompt = false;
  389. // Check if each of the reverse prompts appears at the end of the output.
  390. for (std::string & antiprompt : params.antiprompt) {
  391. if (last_output.find(antiprompt.c_str(), last_output.length() - antiprompt.length(), antiprompt.length()) != std::string::npos) {
  392. is_interacting = true;
  393. is_antiprompt = true;
  394. set_console_color(con_st, CONSOLE_COLOR_USER_INPUT);
  395. fflush(stdout);
  396. break;
  397. }
  398. }
  399. }
  400. if (n_past > 0 && is_interacting) {
  401. // potentially set color to indicate we are taking user input
  402. set_console_color(con_st, CONSOLE_COLOR_USER_INPUT);
  403. #if defined (_WIN32)
  404. // Windows: must reactivate sigint handler after each signal
  405. signal(SIGINT, sigint_handler);
  406. #endif
  407. if (params.instruct) {
  408. printf("\n> ");
  409. }
  410. std::string buffer;
  411. if (!params.input_prefix.empty()) {
  412. buffer += params.input_prefix;
  413. printf("%s", buffer.c_str());
  414. }
  415. std::string line;
  416. bool another_line = true;
  417. do {
  418. #if defined(_WIN32)
  419. std::wstring wline;
  420. if (!std::getline(std::wcin, wline)) {
  421. // input stream is bad or EOF received
  422. return 0;
  423. }
  424. win32_utf8_encode(wline, line);
  425. #else
  426. if (!std::getline(std::cin, line)) {
  427. // input stream is bad or EOF received
  428. return 0;
  429. }
  430. #endif
  431. if (line.empty() || line.back() != '\\') {
  432. another_line = false;
  433. } else {
  434. line.pop_back(); // Remove the continue character
  435. }
  436. buffer += line + '\n'; // Append the line to the result
  437. } while (another_line);
  438. // done taking input, reset color
  439. set_console_color(con_st, CONSOLE_COLOR_DEFAULT);
  440. // Add tokens to embd only if the input buffer is non-empty
  441. // Entering a empty line lets the user pass control back
  442. if (buffer.length() > 1) {
  443. // instruct mode: insert instruction prefix
  444. if (params.instruct && !is_antiprompt) {
  445. n_consumed = embd_inp.size();
  446. embd_inp.insert(embd_inp.end(), inp_pfx.begin(), inp_pfx.end());
  447. }
  448. auto line_inp = ::llama_tokenize(ctx, buffer, false);
  449. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  450. // instruct mode: insert response suffix
  451. if (params.instruct) {
  452. embd_inp.insert(embd_inp.end(), inp_sfx.begin(), inp_sfx.end());
  453. }
  454. n_remain -= line_inp.size();
  455. }
  456. input_noecho = true; // do not echo this again
  457. }
  458. if (n_past > 0) {
  459. is_interacting = false;
  460. }
  461. }
  462. // end of text token
  463. if (!embd.empty() && embd.back() == llama_token_eos()) {
  464. if (params.instruct) {
  465. is_interacting = true;
  466. } else {
  467. fprintf(stderr, " [end of text]\n");
  468. break;
  469. }
  470. }
  471. // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
  472. if (params.interactive && n_remain <= 0 && params.n_predict != -1) {
  473. n_remain = params.n_predict;
  474. is_interacting = true;
  475. }
  476. }
  477. #if defined (_WIN32)
  478. signal(SIGINT, SIG_DFL);
  479. #endif
  480. llama_print_timings(ctx);
  481. llama_free(ctx);
  482. set_console_color(con_st, CONSOLE_COLOR_DEFAULT);
  483. return 0;
  484. }