main.cpp 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  1. #include "common.h"
  2. #include "console.h"
  3. #include "llama.h"
  4. #include <cassert>
  5. #include <cinttypes>
  6. #include <cmath>
  7. #include <cstdio>
  8. #include <cstring>
  9. #include <ctime>
  10. #include <fstream>
  11. #include <iostream>
  12. #include <sstream>
  13. #include <string>
  14. #include <vector>
  15. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  16. #include <signal.h>
  17. #include <unistd.h>
  18. #elif defined (_WIN32)
  19. #define WIN32_LEAN_AND_MEAN
  20. #ifndef NOMINMAX
  21. #define NOMINMAX
  22. #endif
  23. #include <windows.h>
  24. #include <signal.h>
  25. #endif
  26. #if defined(_MSC_VER)
  27. #pragma warning(disable: 4244 4267) // possible loss of data
  28. #endif
  29. static llama_context ** g_ctx;
  30. static llama_model ** g_model;
  31. static gpt_params * g_params;
  32. static std::vector<llama_token> * g_input_tokens;
  33. static std::ostringstream * g_output_ss;
  34. static std::vector<llama_token> * g_output_tokens;
  35. static bool is_interacting = false;
  36. static bool need_insert_eot = false;
  37. static bool file_exists(const std::string & path) {
  38. std::ifstream f(path.c_str());
  39. return f.good();
  40. }
  41. static bool file_is_empty(const std::string & path) {
  42. std::ifstream f;
  43. f.exceptions(std::ifstream::failbit | std::ifstream::badbit);
  44. f.open(path.c_str(), std::ios::in | std::ios::binary | std::ios::ate);
  45. return f.tellg() == 0;
  46. }
  47. static void write_logfile(
  48. const llama_context * ctx, const gpt_params & params, const llama_model * model,
  49. const std::vector<llama_token> & input_tokens, const std::string & output,
  50. const std::vector<llama_token> & output_tokens
  51. ) {
  52. if (params.logdir.empty()) {
  53. return;
  54. }
  55. const std::string timestamp = string_get_sortable_timestamp();
  56. const bool success = fs_create_directory_with_parents(params.logdir);
  57. if (!success) {
  58. fprintf(stderr, "%s: warning: failed to create logdir %s, cannot write logfile\n",
  59. __func__, params.logdir.c_str());
  60. return;
  61. }
  62. const std::string logfile_path = params.logdir + timestamp + ".yml";
  63. FILE * logfile = fopen(logfile_path.c_str(), "w");
  64. if (logfile == NULL) {
  65. fprintf(stderr, "%s: failed to open logfile %s\n", __func__, logfile_path.c_str());
  66. return;
  67. }
  68. fprintf(logfile, "binary: main\n");
  69. char model_desc[128];
  70. llama_model_desc(model, model_desc, sizeof(model_desc));
  71. yaml_dump_non_result_info(logfile, params, ctx, timestamp, input_tokens, model_desc);
  72. fprintf(logfile, "\n");
  73. fprintf(logfile, "######################\n");
  74. fprintf(logfile, "# Generation Results #\n");
  75. fprintf(logfile, "######################\n");
  76. fprintf(logfile, "\n");
  77. yaml_dump_string_multiline(logfile, "output", output.c_str());
  78. yaml_dump_vector_int(logfile, "output_tokens", output_tokens);
  79. llama_dump_timing_info_yaml(logfile, ctx);
  80. fclose(logfile);
  81. }
  82. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  83. static void sigint_handler(int signo) {
  84. if (signo == SIGINT) {
  85. if (!is_interacting && g_params->interactive) {
  86. is_interacting = true;
  87. need_insert_eot = true;
  88. } else {
  89. console::cleanup();
  90. printf("\n");
  91. llama_print_timings(*g_ctx);
  92. write_logfile(*g_ctx, *g_params, *g_model, *g_input_tokens, g_output_ss->str(), *g_output_tokens);
  93. _exit(130);
  94. }
  95. }
  96. }
  97. #endif
  98. static void llama_log_callback_logTee(ggml_log_level level, const char * text, void * user_data) {
  99. (void) level;
  100. (void) user_data;
  101. LOG_TEE("%s", text);
  102. }
  103. static std::string chat_add_and_format(struct llama_model * model, std::vector<llama_chat_msg> & chat_msgs, std::string role, std::string content) {
  104. llama_chat_msg new_msg{role, content};
  105. auto formatted = llama_chat_format_single(
  106. model, g_params->chat_template, chat_msgs, new_msg, role == "user");
  107. chat_msgs.push_back({role, content});
  108. LOG("formatted: %s\n", formatted.c_str());
  109. return formatted;
  110. }
  111. int main(int argc, char ** argv) {
  112. gpt_params params;
  113. g_params = &params;
  114. if (!gpt_params_parse(argc, argv, params)) {
  115. gpt_params_print_usage(argc, argv, params);
  116. return 1;
  117. }
  118. llama_sampling_params & sparams = params.sparams;
  119. #ifndef LOG_DISABLE_LOGS
  120. log_set_target(log_filename_generator("main", "log"));
  121. LOG_TEE("Log start\n");
  122. log_dump_cmdline(argc, argv);
  123. llama_log_set(llama_log_callback_logTee, nullptr);
  124. #endif // LOG_DISABLE_LOGS
  125. // TODO: Dump params ?
  126. //LOG("Params perplexity: %s\n", LOG_TOSTR(params.perplexity));
  127. // save choice to use color for later
  128. // (note for later: this is a slightly awkward choice)
  129. console::init(params.simple_io, params.use_color);
  130. atexit([]() { console::cleanup(); });
  131. if (params.logits_all) {
  132. printf("\n************\n");
  133. printf("%s: please use the 'perplexity' tool for perplexity calculations\n", __func__);
  134. printf("************\n\n");
  135. return 0;
  136. }
  137. if (params.embedding) {
  138. printf("\n************\n");
  139. printf("%s: please use the 'embedding' tool for embedding calculations\n", __func__);
  140. printf("************\n\n");
  141. return 0;
  142. }
  143. if (params.n_ctx != 0 && params.n_ctx < 8) {
  144. LOG_TEE("%s: warning: minimum context size is 8, using minimum size.\n", __func__);
  145. params.n_ctx = 8;
  146. }
  147. if (params.rope_freq_base != 0.0) {
  148. LOG_TEE("%s: warning: changing RoPE frequency base to %g.\n", __func__, params.rope_freq_base);
  149. }
  150. if (params.rope_freq_scale != 0.0) {
  151. LOG_TEE("%s: warning: scaling RoPE frequency by %g.\n", __func__, params.rope_freq_scale);
  152. }
  153. LOG_TEE("%s: build = %d (%s)\n", __func__, LLAMA_BUILD_NUMBER, LLAMA_COMMIT);
  154. LOG_TEE("%s: built with %s for %s\n", __func__, LLAMA_COMPILER, LLAMA_BUILD_TARGET);
  155. if (params.seed == LLAMA_DEFAULT_SEED) {
  156. params.seed = time(NULL);
  157. }
  158. LOG_TEE("%s: seed = %u\n", __func__, params.seed);
  159. std::mt19937 rng(params.seed);
  160. LOG("%s: llama backend init\n", __func__);
  161. llama_backend_init();
  162. llama_numa_init(params.numa);
  163. llama_model * model;
  164. llama_context * ctx;
  165. llama_context * ctx_guidance = NULL;
  166. std::vector<llama_chat_msg> chat_msgs;
  167. g_model = &model;
  168. g_ctx = &ctx;
  169. // load the model and apply lora adapter, if any
  170. LOG("%s: load the model and apply lora adapter, if any\n", __func__);
  171. llama_init_result llama_init = llama_init_from_gpt_params(params);
  172. model = llama_init.model;
  173. ctx = llama_init.context;
  174. if (sparams.cfg_scale > 1.f) {
  175. struct llama_context_params lparams = llama_context_params_from_gpt_params(params);
  176. ctx_guidance = llama_new_context_with_model(model, lparams);
  177. }
  178. if (model == NULL) {
  179. LOG_TEE("%s: error: unable to load model\n", __func__);
  180. return 1;
  181. }
  182. LOG("%s: llama threadpool init = n_threads = %d\n",
  183. __func__,
  184. (int) params.cpuparams.n_threads
  185. );
  186. struct ggml_threadpool_params tpp_batch =
  187. ggml_threadpool_params_from_cpu_params(params.cpuparams_batch);
  188. struct ggml_threadpool_params tpp =
  189. ggml_threadpool_params_from_cpu_params(params.cpuparams);
  190. set_process_priority(params.cpuparams.priority);
  191. struct ggml_threadpool * threadpool_batch = NULL;
  192. if (!ggml_threadpool_params_match(&tpp, &tpp_batch)) {
  193. threadpool_batch = ggml_threadpool_new(&tpp_batch);
  194. if (!threadpool_batch) {
  195. LOG_TEE("%s: batch threadpool create failed : n_threads %d\n", __func__, tpp_batch.n_threads);
  196. exit(1);
  197. }
  198. // Start the non-batch threadpool in the paused state
  199. tpp.paused = true;
  200. }
  201. struct ggml_threadpool * threadpool = ggml_threadpool_new(&tpp);
  202. if (!threadpool) {
  203. LOG_TEE("%s: threadpool create failed : n_threads %d\n", __func__, tpp.n_threads);
  204. exit(1);
  205. }
  206. llama_attach_threadpool(ctx, threadpool, threadpool_batch);
  207. if (ctx_guidance) {
  208. llama_attach_threadpool(ctx_guidance, threadpool, threadpool_batch);
  209. }
  210. const int n_ctx_train = llama_n_ctx_train(model);
  211. const int n_ctx = llama_n_ctx(ctx);
  212. LOG("n_ctx: %d\n", n_ctx);
  213. if (n_ctx > n_ctx_train) {
  214. LOG_TEE("%s: warning: model was trained on only %d context tokens (%d specified)\n",
  215. __func__, n_ctx_train, n_ctx);
  216. }
  217. // print chat template example in conversation mode
  218. if (params.conversation) {
  219. if (params.enable_chat_template) {
  220. LOG_TEE("%s: chat template example: %s\n", __func__, llama_chat_format_example(model, params.chat_template).c_str());
  221. } else {
  222. LOG_TEE("%s: in-suffix/prefix is specified, chat template will be disabled\n", __func__);
  223. }
  224. }
  225. // print system information
  226. {
  227. LOG_TEE("\n");
  228. LOG_TEE("%s\n", gpt_params_get_system_info(params).c_str());
  229. }
  230. std::string path_session = params.path_prompt_cache;
  231. std::vector<llama_token> session_tokens;
  232. if (!path_session.empty()) {
  233. LOG_TEE("%s: attempting to load saved session from '%s'\n", __func__, path_session.c_str());
  234. if (!file_exists(path_session)) {
  235. LOG_TEE("%s: session file does not exist, will create.\n", __func__);
  236. } else if (file_is_empty(path_session)) {
  237. LOG_TEE("%s: The session file is empty. A new session will be initialized.\n", __func__);
  238. } else {
  239. // The file exists and is not empty
  240. session_tokens.resize(n_ctx);
  241. size_t n_token_count_out = 0;
  242. if (!llama_state_load_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.capacity(), &n_token_count_out)) {
  243. LOG_TEE("%s: error: failed to load session file '%s'\n", __func__, path_session.c_str());
  244. return 1;
  245. }
  246. session_tokens.resize(n_token_count_out);
  247. LOG_TEE("%s: loaded a session with prompt size of %d tokens\n", __func__, (int)session_tokens.size());
  248. }
  249. }
  250. const bool add_bos = llama_add_bos_token(model);
  251. if (!llama_model_has_encoder(model)) {
  252. GGML_ASSERT(!llama_add_eos_token(model));
  253. }
  254. LOG("add_bos: %d\n", add_bos);
  255. std::vector<llama_token> embd_inp;
  256. {
  257. auto prompt = (params.conversation && params.enable_chat_template && !params.prompt.empty())
  258. ? chat_add_and_format(model, chat_msgs, "system", params.prompt) // format the system prompt in conversation mode
  259. : params.prompt;
  260. if (params.interactive_first || !params.prompt.empty() || session_tokens.empty()) {
  261. LOG("tokenize the prompt\n");
  262. embd_inp = ::llama_tokenize(ctx, prompt, true, true);
  263. } else {
  264. LOG("use session tokens\n");
  265. embd_inp = session_tokens;
  266. }
  267. LOG("prompt: \"%s\"\n", log_tostr(prompt));
  268. LOG("tokens: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd_inp).c_str());
  269. }
  270. // Should not run without any tokens
  271. if (embd_inp.empty()) {
  272. if (add_bos) {
  273. embd_inp.push_back(llama_token_bos(model));
  274. LOG("embd_inp was considered empty and bos was added: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd_inp).c_str());
  275. } else {
  276. LOG_TEE("error: input is empty\n");
  277. return -1;
  278. }
  279. }
  280. // Tokenize negative prompt
  281. std::vector<llama_token> guidance_inp;
  282. int guidance_offset = 0;
  283. int original_prompt_len = 0;
  284. if (ctx_guidance) {
  285. LOG("cfg_negative_prompt: \"%s\"\n", log_tostr(sparams.cfg_negative_prompt));
  286. guidance_inp = ::llama_tokenize(ctx_guidance, sparams.cfg_negative_prompt, true, true);
  287. LOG("guidance_inp tokenized: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx_guidance, guidance_inp).c_str());
  288. std::vector<llama_token> original_inp = ::llama_tokenize(ctx, params.prompt, true, true);
  289. LOG("original_inp tokenized: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, original_inp).c_str());
  290. original_prompt_len = original_inp.size();
  291. guidance_offset = (int)guidance_inp.size() - original_prompt_len;
  292. LOG("original_prompt_len: %s", log_tostr(original_prompt_len));
  293. LOG("guidance_offset: %s", log_tostr(guidance_offset));
  294. }
  295. if ((int) embd_inp.size() > n_ctx - 4) {
  296. LOG_TEE("%s: error: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4);
  297. return 1;
  298. }
  299. // debug message about similarity of saved session, if applicable
  300. size_t n_matching_session_tokens = 0;
  301. if (!session_tokens.empty()) {
  302. for (llama_token id : session_tokens) {
  303. if (n_matching_session_tokens >= embd_inp.size() || id != embd_inp[n_matching_session_tokens]) {
  304. break;
  305. }
  306. n_matching_session_tokens++;
  307. }
  308. if (params.prompt.empty() && n_matching_session_tokens == embd_inp.size()) {
  309. LOG_TEE("%s: using full prompt from session file\n", __func__);
  310. } else if (n_matching_session_tokens >= embd_inp.size()) {
  311. LOG_TEE("%s: session file has exact match for prompt!\n", __func__);
  312. } else if (n_matching_session_tokens < (embd_inp.size() / 2)) {
  313. LOG_TEE("%s: warning: session file has low similarity to prompt (%zu / %zu tokens); will mostly be reevaluated\n",
  314. __func__, n_matching_session_tokens, embd_inp.size());
  315. } else {
  316. LOG_TEE("%s: session file matches %zu / %zu tokens of prompt\n",
  317. __func__, n_matching_session_tokens, embd_inp.size());
  318. }
  319. // remove any "future" tokens that we might have inherited from the previous session
  320. llama_kv_cache_seq_rm(ctx, -1, n_matching_session_tokens, -1);
  321. }
  322. LOGLN(
  323. "recalculate the cached logits (check): embd_inp.empty() %s, n_matching_session_tokens %zu, embd_inp.size() %zu, session_tokens.size() %zu, embd_inp.size() %zu",
  324. log_tostr(embd_inp.empty()), n_matching_session_tokens, embd_inp.size(), session_tokens.size(), embd_inp.size());
  325. // if we will use the cache for the full prompt without reaching the end of the cache, force
  326. // reevaluation of the last token to recalculate the cached logits
  327. if (!embd_inp.empty() && n_matching_session_tokens == embd_inp.size() && session_tokens.size() > embd_inp.size()) {
  328. LOGLN("recalculate the cached logits (do): session_tokens.resize( %zu )", embd_inp.size() - 1);
  329. session_tokens.resize(embd_inp.size() - 1);
  330. }
  331. // number of tokens to keep when resetting context
  332. if (params.n_keep < 0 || params.n_keep > (int) embd_inp.size()) {
  333. params.n_keep = (int)embd_inp.size();
  334. } else {
  335. params.n_keep += add_bos; // always keep the BOS token
  336. }
  337. if (params.conversation) {
  338. params.interactive_first = true;
  339. }
  340. // enable interactive mode if interactive start is specified
  341. if (params.interactive_first) {
  342. params.interactive = true;
  343. }
  344. if (params.verbose_prompt) {
  345. LOG_TEE("\n");
  346. LOG_TEE("%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  347. LOG_TEE("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  348. for (int i = 0; i < (int) embd_inp.size(); i++) {
  349. LOG_TEE("%6d -> '%s'\n", embd_inp[i], llama_token_to_piece(ctx, embd_inp[i]).c_str());
  350. }
  351. if (ctx_guidance) {
  352. LOG_TEE("\n");
  353. LOG_TEE("%s: negative prompt: '%s'\n", __func__, sparams.cfg_negative_prompt.c_str());
  354. LOG_TEE("%s: number of tokens in negative prompt = %zu\n", __func__, guidance_inp.size());
  355. for (int i = 0; i < (int) guidance_inp.size(); i++) {
  356. LOG_TEE("%6d -> '%s'\n", guidance_inp[i], llama_token_to_piece(ctx, guidance_inp[i]).c_str());
  357. }
  358. }
  359. if (params.n_keep > add_bos) {
  360. LOG_TEE("%s: static prompt based on n_keep: '", __func__);
  361. for (int i = 0; i < params.n_keep; i++) {
  362. LOG_TEE("%s", llama_token_to_piece(ctx, embd_inp[i]).c_str());
  363. }
  364. LOG_TEE("'\n");
  365. }
  366. LOG_TEE("\n");
  367. }
  368. // ctrl+C handling
  369. {
  370. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  371. struct sigaction sigint_action;
  372. sigint_action.sa_handler = sigint_handler;
  373. sigemptyset (&sigint_action.sa_mask);
  374. sigint_action.sa_flags = 0;
  375. sigaction(SIGINT, &sigint_action, NULL);
  376. #elif defined (_WIN32)
  377. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  378. return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
  379. };
  380. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  381. #endif
  382. }
  383. if (params.interactive) {
  384. LOG_TEE("%s: interactive mode on.\n", __func__);
  385. if (!params.antiprompt.empty()) {
  386. for (const auto & antiprompt : params.antiprompt) {
  387. LOG_TEE("Reverse prompt: '%s'\n", antiprompt.c_str());
  388. if (params.verbose_prompt) {
  389. auto tmp = ::llama_tokenize(ctx, antiprompt, false, true);
  390. for (int i = 0; i < (int) tmp.size(); i++) {
  391. LOG_TEE("%6d -> '%s'\n", tmp[i], llama_token_to_piece(ctx, tmp[i]).c_str());
  392. }
  393. }
  394. }
  395. }
  396. if (params.input_prefix_bos) {
  397. LOG_TEE("Input prefix with BOS\n");
  398. }
  399. if (!params.input_prefix.empty()) {
  400. LOG_TEE("Input prefix: '%s'\n", params.input_prefix.c_str());
  401. if (params.verbose_prompt) {
  402. auto tmp = ::llama_tokenize(ctx, params.input_prefix, true, true);
  403. for (int i = 0; i < (int) tmp.size(); i++) {
  404. LOG_TEE("%6d -> '%s'\n", tmp[i], llama_token_to_piece(ctx, tmp[i]).c_str());
  405. }
  406. }
  407. }
  408. if (!params.input_suffix.empty()) {
  409. LOG_TEE("Input suffix: '%s'\n", params.input_suffix.c_str());
  410. if (params.verbose_prompt) {
  411. auto tmp = ::llama_tokenize(ctx, params.input_suffix, false, true);
  412. for (int i = 0; i < (int) tmp.size(); i++) {
  413. LOG_TEE("%6d -> '%s'\n", tmp[i], llama_token_to_piece(ctx, tmp[i]).c_str());
  414. }
  415. }
  416. }
  417. }
  418. LOG_TEE("sampling: \n%s\n", llama_sampling_print(sparams).c_str());
  419. LOG_TEE("sampling order: \n%s\n", llama_sampling_order_print(sparams).c_str());
  420. LOG_TEE("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);
  421. // group-attention state
  422. // number of grouped KV tokens so far (used only if params.grp_attn_n > 1)
  423. int ga_i = 0;
  424. const int ga_n = params.grp_attn_n;
  425. const int ga_w = params.grp_attn_w;
  426. if (ga_n != 1) {
  427. GGML_ASSERT(ga_n > 0 && "grp_attn_n must be positive"); // NOLINT
  428. GGML_ASSERT(ga_w % ga_n == 0 && "grp_attn_w must be a multiple of grp_attn_n"); // NOLINT
  429. //GGML_ASSERT(n_ctx_train % ga_w == 0 && "n_ctx_train must be a multiple of grp_attn_w"); // NOLINT
  430. //GGML_ASSERT(n_ctx >= n_ctx_train * ga_n && "n_ctx must be at least n_ctx_train * grp_attn_n"); // NOLINT
  431. LOG_TEE("self-extend: n_ctx_train = %d, grp_attn_n = %d, grp_attn_w = %d\n", n_ctx_train, ga_n, ga_w);
  432. }
  433. LOG_TEE("\n\n");
  434. if (params.interactive) {
  435. const char * control_message;
  436. if (params.multiline_input) {
  437. control_message = " - To return control to the AI, end your input with '\\'.\n"
  438. " - To return control without starting a new line, end your input with '/'.\n";
  439. } else {
  440. control_message = " - Press Return to return control to the AI.\n"
  441. " - To return control without starting a new line, end your input with '/'.\n"
  442. " - If you want to submit another line, end your input with '\\'.\n";
  443. }
  444. LOG_TEE("== Running in interactive mode. ==\n");
  445. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  446. LOG_TEE( " - Press Ctrl+C to interject at any time.\n");
  447. #endif
  448. LOG_TEE( "%s\n", control_message);
  449. is_interacting = params.interactive_first;
  450. }
  451. bool is_antiprompt = false;
  452. bool input_echo = true;
  453. bool display = true;
  454. bool need_to_save_session = !path_session.empty() && n_matching_session_tokens < embd_inp.size();
  455. int n_past = 0;
  456. int n_remain = params.n_predict;
  457. int n_consumed = 0;
  458. int n_session_consumed = 0;
  459. int n_past_guidance = 0;
  460. std::vector<int> input_tokens; g_input_tokens = &input_tokens;
  461. std::vector<int> output_tokens; g_output_tokens = &output_tokens;
  462. std::ostringstream output_ss; g_output_ss = &output_ss;
  463. std::ostringstream assistant_ss; // for storing current assistant message, used in conversation mode
  464. // the first thing we will do is to output the prompt, so set color accordingly
  465. console::set_display(console::prompt);
  466. display = params.display_prompt;
  467. std::vector<llama_token> embd;
  468. std::vector<llama_token> embd_guidance;
  469. // tokenized antiprompts
  470. std::vector<std::vector<llama_token>> antiprompt_ids;
  471. antiprompt_ids.reserve(params.antiprompt.size());
  472. for (const std::string & antiprompt : params.antiprompt) {
  473. antiprompt_ids.emplace_back(::llama_tokenize(ctx, antiprompt, false, true));
  474. }
  475. struct llama_sampling_context * ctx_sampling = llama_sampling_init(sparams);
  476. if (!ctx_sampling) {
  477. fprintf(stderr, "%s: failed to initialize sampling subsystem\n", __func__);
  478. exit(1);
  479. }
  480. if (llama_model_has_encoder(model)) {
  481. int enc_input_size = embd_inp.size();
  482. llama_token * enc_input_buf = embd_inp.data();
  483. if (llama_encode(ctx, llama_batch_get_one(enc_input_buf, enc_input_size, 0, 0))) {
  484. LOG_TEE("%s : failed to eval\n", __func__);
  485. return 1;
  486. }
  487. llama_token decoder_start_token_id = llama_model_decoder_start_token(model);
  488. if (decoder_start_token_id == -1) {
  489. decoder_start_token_id = llama_token_bos(model);
  490. }
  491. embd_inp.clear();
  492. embd_inp.push_back(decoder_start_token_id);
  493. }
  494. while ((n_remain != 0 && !is_antiprompt) || params.interactive) {
  495. // predict
  496. if (!embd.empty()) {
  497. // Note: (n_ctx - 4) here is to match the logic for commandline prompt handling via
  498. // --prompt or --file which uses the same value.
  499. int max_embd_size = n_ctx - 4;
  500. // Ensure the input doesn't exceed the context size by truncating embd if necessary.
  501. if ((int) embd.size() > max_embd_size) {
  502. const int skipped_tokens = (int) embd.size() - max_embd_size;
  503. embd.resize(max_embd_size);
  504. console::set_display(console::error);
  505. printf("<<input too long: skipped %d token%s>>", skipped_tokens, skipped_tokens != 1 ? "s" : "");
  506. console::set_display(console::reset);
  507. fflush(stdout);
  508. }
  509. if (ga_n == 1) {
  510. // infinite text generation via context shifting
  511. // if we run out of context:
  512. // - take the n_keep first tokens from the original prompt (via n_past)
  513. // - take half of the last (n_ctx - n_keep) tokens and recompute the logits in batches
  514. if (n_past + (int) embd.size() + std::max<int>(0, guidance_offset) >= n_ctx) {
  515. if (params.n_predict == -2) {
  516. LOG_TEE("\n\n%s: context full and n_predict == -%d => stopping\n", __func__, params.n_predict);
  517. break;
  518. }
  519. const int n_left = n_past - params.n_keep;
  520. const int n_discard = n_left/2;
  521. LOG("context full, swapping: n_past = %d, n_left = %d, n_ctx = %d, n_keep = %d, n_discard = %d\n",
  522. n_past, n_left, n_ctx, params.n_keep, n_discard);
  523. llama_kv_cache_seq_rm (ctx, 0, params.n_keep , params.n_keep + n_discard);
  524. llama_kv_cache_seq_add(ctx, 0, params.n_keep + n_discard, n_past, -n_discard);
  525. n_past -= n_discard;
  526. if (ctx_guidance) {
  527. n_past_guidance -= n_discard;
  528. }
  529. LOG("after swap: n_past = %d, n_past_guidance = %d\n", n_past, n_past_guidance);
  530. LOG("embd: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd).c_str());
  531. LOG("clear session path\n");
  532. path_session.clear();
  533. }
  534. } else {
  535. // context extension via Self-Extend
  536. while (n_past >= ga_i + ga_w) {
  537. const int ib = (ga_n*ga_i)/ga_w;
  538. const int bd = (ga_w/ga_n)*(ga_n - 1);
  539. const int dd = (ga_w/ga_n) - ib*bd - ga_w;
  540. LOG("\n");
  541. LOG("shift: [%6d, %6d] + %6d -> [%6d, %6d]\n", ga_i, n_past, ib*bd, ga_i + ib*bd, n_past + ib*bd);
  542. LOG("div: [%6d, %6d] / %6d -> [%6d, %6d]\n", ga_i + ib*bd, ga_i + ib*bd + ga_w, ga_n, (ga_i + ib*bd)/ga_n, (ga_i + ib*bd + ga_w)/ga_n);
  543. LOG("shift: [%6d, %6d] + %6d -> [%6d, %6d]\n", ga_i + ib*bd + ga_w, n_past + ib*bd, dd, ga_i + ib*bd + ga_w + dd, n_past + ib*bd + dd);
  544. llama_kv_cache_seq_add(ctx, 0, ga_i, n_past, ib*bd);
  545. llama_kv_cache_seq_div(ctx, 0, ga_i + ib*bd, ga_i + ib*bd + ga_w, ga_n);
  546. llama_kv_cache_seq_add(ctx, 0, ga_i + ib*bd + ga_w, n_past + ib*bd, dd);
  547. n_past -= bd;
  548. ga_i += ga_w/ga_n;
  549. LOG("\nn_past_old = %d, n_past = %d, ga_i = %d\n\n", n_past + bd, n_past, ga_i);
  550. }
  551. }
  552. // try to reuse a matching prefix from the loaded session instead of re-eval (via n_past)
  553. if (n_session_consumed < (int) session_tokens.size()) {
  554. size_t i = 0;
  555. for ( ; i < embd.size(); i++) {
  556. if (embd[i] != session_tokens[n_session_consumed]) {
  557. session_tokens.resize(n_session_consumed);
  558. break;
  559. }
  560. n_past++;
  561. n_session_consumed++;
  562. if (n_session_consumed >= (int) session_tokens.size()) {
  563. ++i;
  564. break;
  565. }
  566. }
  567. if (i > 0) {
  568. embd.erase(embd.begin(), embd.begin() + i);
  569. }
  570. }
  571. // evaluate tokens in batches
  572. // embd is typically prepared beforehand to fit within a batch, but not always
  573. if (ctx_guidance) {
  574. int input_size = 0;
  575. llama_token * input_buf = NULL;
  576. if (n_past_guidance < (int) guidance_inp.size()) {
  577. // Guidance context should have the same data with these modifications:
  578. //
  579. // * Replace the initial prompt
  580. // * Shift everything by guidance_offset
  581. embd_guidance = guidance_inp;
  582. if (embd.begin() + original_prompt_len < embd.end()) {
  583. embd_guidance.insert(
  584. embd_guidance.end(),
  585. embd.begin() + original_prompt_len,
  586. embd.end()
  587. );
  588. }
  589. input_buf = embd_guidance.data();
  590. input_size = embd_guidance.size();
  591. LOG("guidance context: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd_guidance).c_str());
  592. } else {
  593. input_buf = embd.data();
  594. input_size = embd.size();
  595. }
  596. for (int i = 0; i < input_size; i += params.n_batch) {
  597. int n_eval = std::min(input_size - i, params.n_batch);
  598. if (llama_decode(ctx_guidance, llama_batch_get_one(input_buf + i, n_eval, n_past_guidance, 0))) {
  599. LOG_TEE("%s : failed to eval\n", __func__);
  600. return 1;
  601. }
  602. n_past_guidance += n_eval;
  603. }
  604. }
  605. for (int i = 0; i < (int) embd.size(); i += params.n_batch) {
  606. int n_eval = (int) embd.size() - i;
  607. if (n_eval > params.n_batch) {
  608. n_eval = params.n_batch;
  609. }
  610. LOG("eval: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd).c_str());
  611. if (llama_decode(ctx, llama_batch_get_one(&embd[i], n_eval, n_past, 0))) {
  612. LOG_TEE("%s : failed to eval\n", __func__);
  613. return 1;
  614. }
  615. n_past += n_eval;
  616. LOG("n_past = %d\n", n_past);
  617. // Display total tokens alongside total time
  618. if (params.n_print > 0 && n_past % params.n_print == 0) {
  619. LOG_TEE("\n\033[31mTokens consumed so far = %d / %d \033[0m\n", n_past, n_ctx);
  620. }
  621. }
  622. if (!embd.empty() && !path_session.empty()) {
  623. session_tokens.insert(session_tokens.end(), embd.begin(), embd.end());
  624. n_session_consumed = session_tokens.size();
  625. }
  626. }
  627. embd.clear();
  628. embd_guidance.clear();
  629. if ((int) embd_inp.size() <= n_consumed && !is_interacting) {
  630. // optionally save the session on first sample (for faster prompt loading next time)
  631. if (!path_session.empty() && need_to_save_session && !params.prompt_cache_ro) {
  632. need_to_save_session = false;
  633. llama_state_save_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
  634. LOG("saved session to %s\n", path_session.c_str());
  635. }
  636. const llama_token id = llama_sampling_sample(ctx_sampling, ctx, ctx_guidance);
  637. llama_sampling_accept(ctx_sampling, ctx, id, /* apply_grammar= */ true);
  638. LOG("last: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, ctx_sampling->prev).c_str());
  639. embd.push_back(id);
  640. // echo this to console
  641. input_echo = true;
  642. // decrement remaining sampling budget
  643. --n_remain;
  644. LOG("n_remain: %d\n", n_remain);
  645. } else {
  646. // some user input remains from prompt or interaction, forward it to processing
  647. LOG("embd_inp.size(): %d, n_consumed: %d\n", (int) embd_inp.size(), n_consumed);
  648. while ((int) embd_inp.size() > n_consumed) {
  649. embd.push_back(embd_inp[n_consumed]);
  650. // push the prompt in the sampling context in order to apply repetition penalties later
  651. // for the prompt, we don't apply grammar rules
  652. llama_sampling_accept(ctx_sampling, ctx, embd_inp[n_consumed], /* apply_grammar= */ false);
  653. ++n_consumed;
  654. if ((int) embd.size() >= params.n_batch) {
  655. break;
  656. }
  657. }
  658. }
  659. // display text
  660. if (input_echo && display) {
  661. for (auto id : embd) {
  662. const std::string token_str = llama_token_to_piece(ctx, id, params.special);
  663. // Console/Stream Output
  664. fprintf(stdout, "%s", token_str.c_str());
  665. // Record Displayed Tokens To Log
  666. // Note: Generated tokens are created one by one hence this check
  667. if (embd.size() > 1) {
  668. // Incoming Requested Tokens
  669. input_tokens.push_back(id);
  670. } else {
  671. // Outgoing Generated Tokens
  672. output_tokens.push_back(id);
  673. output_ss << token_str;
  674. }
  675. fflush(stdout);
  676. }
  677. }
  678. // reset color to default if there is no pending user input
  679. if (input_echo && (int) embd_inp.size() == n_consumed) {
  680. console::set_display(console::reset);
  681. display = true;
  682. }
  683. // if not currently processing queued inputs;
  684. if ((int) embd_inp.size() <= n_consumed) {
  685. // check for reverse prompt in the last n_prev tokens
  686. if (!params.antiprompt.empty()) {
  687. const int n_prev = 32;
  688. const std::string last_output = llama_sampling_prev_str(ctx_sampling, ctx, n_prev);
  689. is_antiprompt = false;
  690. // Check if each of the reverse prompts appears at the end of the output.
  691. // If we're not running interactively, the reverse prompt might be tokenized with some following characters
  692. // so we'll compensate for that by widening the search window a bit.
  693. for (std::string & antiprompt : params.antiprompt) {
  694. size_t extra_padding = params.interactive ? 0 : 2;
  695. size_t search_start_pos = last_output.length() > static_cast<size_t>(antiprompt.length() + extra_padding)
  696. ? last_output.length() - static_cast<size_t>(antiprompt.length() + extra_padding)
  697. : 0;
  698. if (last_output.find(antiprompt, search_start_pos) != std::string::npos) {
  699. if (params.interactive) {
  700. is_interacting = true;
  701. }
  702. is_antiprompt = true;
  703. break;
  704. }
  705. }
  706. // check for reverse prompt using special tokens
  707. llama_token last_token = llama_sampling_last(ctx_sampling);
  708. for (std::vector<llama_token> ids : antiprompt_ids) {
  709. if (ids.size() == 1 && last_token == ids[0]) {
  710. if (params.interactive) {
  711. is_interacting = true;
  712. }
  713. is_antiprompt = true;
  714. break;
  715. }
  716. }
  717. if (is_antiprompt) {
  718. LOG("found antiprompt: %s\n", last_output.c_str());
  719. }
  720. }
  721. // deal with end of generation tokens in interactive mode
  722. if (llama_token_is_eog(model, llama_sampling_last(ctx_sampling))) {
  723. LOG("found an EOG token\n");
  724. if (params.interactive) {
  725. if (!params.antiprompt.empty()) {
  726. // tokenize and inject first reverse prompt
  727. const auto first_antiprompt = ::llama_tokenize(ctx, params.antiprompt.front(), false, true);
  728. embd_inp.insert(embd_inp.end(), first_antiprompt.begin(), first_antiprompt.end());
  729. is_antiprompt = true;
  730. }
  731. if (params.enable_chat_template) {
  732. chat_add_and_format(model, chat_msgs, "assistant", assistant_ss.str());
  733. }
  734. is_interacting = true;
  735. printf("\n");
  736. }
  737. }
  738. // if current token is not EOG, we add it to current assistant message
  739. if (params.conversation) {
  740. auto id = llama_sampling_last(ctx_sampling);
  741. assistant_ss << llama_token_to_piece(ctx, id, false);
  742. }
  743. if (n_past > 0 && is_interacting) {
  744. LOG("waiting for user input\n");
  745. if (params.conversation) {
  746. printf("\n> ");
  747. }
  748. if (params.input_prefix_bos) {
  749. LOG("adding input prefix BOS token\n");
  750. embd_inp.push_back(llama_token_bos(model));
  751. }
  752. std::string buffer;
  753. if (!params.input_prefix.empty() && !params.conversation) {
  754. LOG("appending input prefix: '%s'\n", params.input_prefix.c_str());
  755. printf("%s", params.input_prefix.c_str());
  756. }
  757. // color user input only
  758. console::set_display(console::user_input);
  759. display = params.display_prompt;
  760. std::string line;
  761. bool another_line = true;
  762. do {
  763. another_line = console::readline(line, params.multiline_input);
  764. buffer += line;
  765. } while (another_line);
  766. // done taking input, reset color
  767. console::set_display(console::reset);
  768. display = true;
  769. // Add tokens to embd only if the input buffer is non-empty
  770. // Entering a empty line lets the user pass control back
  771. if (buffer.length() > 1) {
  772. // append input suffix if any
  773. if (!params.input_suffix.empty() && !params.conversation) {
  774. LOG("appending input suffix: '%s'\n", params.input_suffix.c_str());
  775. printf("%s", params.input_suffix.c_str());
  776. }
  777. LOG("buffer: '%s'\n", buffer.c_str());
  778. const size_t original_size = embd_inp.size();
  779. if (params.escape) {
  780. string_process_escapes(buffer);
  781. }
  782. bool format_chat = params.conversation && params.enable_chat_template;
  783. std::string user_inp = format_chat
  784. ? chat_add_and_format(model, chat_msgs, "user", std::move(buffer))
  785. : std::move(buffer);
  786. // TODO: one inconvenient of current chat template implementation is that we can't distinguish between user input and special tokens (prefix/postfix)
  787. const auto line_pfx = ::llama_tokenize(ctx, params.input_prefix, false, true);
  788. const auto line_inp = ::llama_tokenize(ctx, user_inp, false, format_chat);
  789. const auto line_sfx = ::llama_tokenize(ctx, params.input_suffix, false, true);
  790. LOG("input tokens: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, line_inp).c_str());
  791. // if user stop generation mid-way, we must add EOT to finish model's last response
  792. if (need_insert_eot && format_chat) {
  793. llama_token eot = llama_token_eot(model);
  794. embd_inp.push_back(eot == -1 ? llama_token_eos(model) : eot);
  795. need_insert_eot = false;
  796. }
  797. embd_inp.insert(embd_inp.end(), line_pfx.begin(), line_pfx.end());
  798. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  799. embd_inp.insert(embd_inp.end(), line_sfx.begin(), line_sfx.end());
  800. for (size_t i = original_size; i < embd_inp.size(); ++i) {
  801. const llama_token token = embd_inp[i];
  802. output_tokens.push_back(token);
  803. output_ss << llama_token_to_piece(ctx, token);
  804. }
  805. // reset assistant message
  806. assistant_ss.str("");
  807. n_remain -= line_inp.size();
  808. LOG("n_remain: %d\n", n_remain);
  809. } else {
  810. LOG("empty line, passing control back\n");
  811. }
  812. input_echo = false; // do not echo this again
  813. }
  814. if (n_past > 0) {
  815. if (is_interacting) {
  816. llama_sampling_reset(ctx_sampling);
  817. }
  818. is_interacting = false;
  819. }
  820. }
  821. // end of generation
  822. if (!embd.empty() && llama_token_is_eog(model, embd.back()) && !(params.interactive)) {
  823. LOG_TEE(" [end of text]\n");
  824. break;
  825. }
  826. // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
  827. // We skip this logic when n_predict == -1 (infinite) or -2 (stop at context size).
  828. if (params.interactive && n_remain <= 0 && params.n_predict >= 0) {
  829. n_remain = params.n_predict;
  830. is_interacting = true;
  831. }
  832. }
  833. if (!path_session.empty() && params.prompt_cache_all && !params.prompt_cache_ro) {
  834. LOG_TEE("\n%s: saving final output to session file '%s'\n", __func__, path_session.c_str());
  835. llama_state_save_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
  836. }
  837. llama_print_timings(ctx);
  838. write_logfile(ctx, params, model, input_tokens, output_ss.str(), output_tokens);
  839. if (ctx_guidance) { llama_free(ctx_guidance); }
  840. llama_free(ctx);
  841. llama_free_model(model);
  842. llama_sampling_free(ctx_sampling);
  843. llama_backend_free();
  844. ggml_threadpool_free(threadpool);
  845. ggml_threadpool_free(threadpool_batch);
  846. #ifndef LOG_DISABLE_LOGS
  847. LOG_TEE("Log end\n");
  848. #endif // LOG_DISABLE_LOGS
  849. return 0;
  850. }