main.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  1. #include "arg.h"
  2. #include "common.h"
  3. #include "console.h"
  4. #include "log.h"
  5. #include "sampling.h"
  6. #include "llama.h"
  7. #include "chat.h"
  8. #include <cstdio>
  9. #include <cstring>
  10. #include <ctime>
  11. #include <fstream>
  12. #include <iostream>
  13. #include <sstream>
  14. #include <string>
  15. #include <vector>
  16. #include <mutex>
  17. // Forward declarations for internal cache access
  18. struct llama_memory_hybrid;
  19. struct llama_memory_recurrent;
  20. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  21. #include <signal.h>
  22. #include <unistd.h>
  23. #elif defined (_WIN32)
  24. #define WIN32_LEAN_AND_MEAN
  25. #ifndef NOMINMAX
  26. #define NOMINMAX
  27. #endif
  28. #include <windows.h>
  29. #include <signal.h>
  30. #endif
  31. #if defined(_MSC_VER)
  32. #pragma warning(disable: 4244 4267) // possible loss of data
  33. #endif
  34. static llama_context ** g_ctx;
  35. static llama_model ** g_model;
  36. static common_sampler ** g_smpl;
  37. static common_params * g_params;
  38. static std::vector<llama_token> * g_input_tokens;
  39. static std::ostringstream * g_output_ss;
  40. static std::vector<llama_token> * g_output_tokens;
  41. static bool is_interacting = false;
  42. static bool need_insert_eot = false;
  43. static bool print_cache_stats = false;
  44. static int token_count = 0;
  45. static void print_usage(int argc, char ** argv) {
  46. (void) argc;
  47. LOG("\nexample usage:\n");
  48. LOG("\n text generation: %s -m your_model.gguf -p \"I believe the meaning of life is\" -n 128 -no-cnv\n", argv[0]);
  49. LOG("\n chat (conversation): %s -m your_model.gguf -sys \"You are a helpful assistant\"\n", argv[0]);
  50. LOG("\n");
  51. }
  52. static bool file_exists(const std::string & path) {
  53. std::ifstream f(path.c_str());
  54. return f.good();
  55. }
  56. static bool file_is_empty(const std::string & path) {
  57. std::ifstream f;
  58. f.exceptions(std::ifstream::failbit | std::ifstream::badbit);
  59. f.open(path.c_str(), std::ios::in | std::ios::binary | std::ios::ate);
  60. return f.tellg() == 0;
  61. }
  62. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  63. static void sigint_handler(int signo) {
  64. if (signo == SIGINT) {
  65. if (!is_interacting && g_params->interactive) {
  66. is_interacting = true;
  67. need_insert_eot = true;
  68. } else {
  69. console::cleanup();
  70. LOG("\n");
  71. common_perf_print(*g_ctx, *g_smpl);
  72. // make sure all logs are flushed
  73. LOG("Interrupted by user\n");
  74. common_log_pause(common_log_main());
  75. _exit(130);
  76. }
  77. }
  78. }
  79. #endif
  80. struct callback_data {
  81. std::vector<uint8_t> data;
  82. std::map<std::string, int32_t> tensors;
  83. std::mutex mutex;
  84. };
  85. static std::string ggml_ne_string(const ggml_tensor * t) {
  86. std::string str;
  87. for (int i = 0; i < GGML_MAX_DIMS; ++i) {
  88. str += std::to_string(t->ne[i]);
  89. if (i + 1 < GGML_MAX_DIMS) {
  90. str += ", ";
  91. }
  92. }
  93. return str;
  94. }
  95. static inline float ggml_compute_bf16_to_fp32(ggml_bf16_t h) {
  96. union {
  97. float f;
  98. uint32_t i;
  99. } u;
  100. u.i = (uint32_t)h.bits << 16;
  101. return u.f;
  102. }
  103. static float ggml_get_float_value(uint8_t * data, ggml_type type, const size_t * nb, size_t i0, size_t i1, size_t i2, size_t i3) {
  104. size_t i = i3 * nb[3] + i2 * nb[2] + i1 * nb[1] + i0 * nb[0];
  105. float v;
  106. if (type == GGML_TYPE_F16) {
  107. v = ggml_fp16_to_fp32(*(ggml_fp16_t *) &data[i]);
  108. } else if (type == GGML_TYPE_F32) {
  109. v = *(float *) &data[i];
  110. } else if (type == GGML_TYPE_I64) {
  111. v = (float) *(int64_t *) &data[i];
  112. } else if (type == GGML_TYPE_I32) {
  113. v = (float) *(int32_t *) &data[i];
  114. } else if (type == GGML_TYPE_I16) {
  115. v = (float) *(int16_t *) &data[i];
  116. } else if (type == GGML_TYPE_I8) {
  117. v = (float) *(int8_t *) &data[i];
  118. } else if (type == GGML_TYPE_BF16) {
  119. v = ggml_compute_bf16_to_fp32(*(ggml_bf16_t *) &data[i]);
  120. } else {
  121. GGML_ABORT("fatal error");
  122. }
  123. return v;
  124. }
  125. // Function to save a tensor to binary file
  126. static void save_tensor(struct ggml_tensor * tensor, uint8_t * data, const char * filename) {
  127. FILE* f = fopen((std::string("reference/tensors/conv/") + std::string(filename)).c_str(), "wb");
  128. if (!f) {
  129. fprintf(stderr, "Failed to create file: %s\n", filename);
  130. return;
  131. }
  132. // Write shape
  133. fwrite(tensor->ne, sizeof(int64_t), 4, f);
  134. // Calculate total elements
  135. int64_t total_elements = tensor->ne[0] * tensor->ne[1] * tensor->ne[2] * tensor->ne[3];
  136. // Write data
  137. fwrite(data, sizeof(float), total_elements, f);
  138. fclose(f);
  139. }
  140. static void ggml_print_tensor(uint8_t * data, ggml_type type, const int64_t * ne, const size_t * nb, int64_t n) {
  141. GGML_ASSERT(n > 0);
  142. double sum = 0;
  143. for (int64_t i3 = 0; i3 < ne[3]; i3++) {
  144. for (int64_t i2 = 0; i2 < ne[2]; i2++) {
  145. for (int64_t i1 = 0; i1 < ne[1]; i1++) {
  146. for (int64_t i0 = 0; i0 < ne[0]; i0++) {
  147. const float v = ggml_get_float_value(data, type, nb, i0, i1, i2, i3);
  148. sum += v;
  149. }
  150. }
  151. }
  152. }
  153. for (int64_t i3 = 0; i3 < ne[3]; i3++) {
  154. LOG(" [\n");
  155. for (int64_t i2 = 0; i2 < ne[2]; i2++) {
  156. if (i2 == n && ne[2] > 2*n) {
  157. LOG(" ..., \n");
  158. i2 = ne[2] - n;
  159. }
  160. LOG(" [\n");
  161. for (int64_t i1 = 0; i1 < ne[1]; i1++) {
  162. if (i1 == n && ne[1] > 2*n) {
  163. LOG(" ..., \n");
  164. i1 = ne[1] - n;
  165. }
  166. LOG(" [");
  167. for (int64_t i0 = 0; i0 < ne[0]; i0++) {
  168. if (i0 == n && ne[0] > 2*n) {
  169. LOG("..., ");
  170. i0 = ne[0] - n;
  171. }
  172. const float v = ggml_get_float_value(data, type, nb, i0, i1, i2, i3);
  173. LOG("%12.4f", v);
  174. if (i0 < ne[0] - 1) LOG(", ");
  175. }
  176. LOG("],\n");
  177. }
  178. LOG(" ],\n");
  179. }
  180. LOG(" ]\n");
  181. LOG(" sum = %f\n", sum);
  182. }
  183. // TODO: make this abort configurable/optional?
  184. if (std::isnan(sum)) {
  185. LOG_ERR("encountered NaN - aborting\n");
  186. exit(0);
  187. }
  188. }
  189. static bool ggml_debug(struct ggml_tensor * t, bool ask, void * user_data) {
  190. auto * cb_data = (callback_data *) user_data;
  191. std::lock_guard<std::mutex> lock(cb_data->mutex);
  192. const struct ggml_tensor * src0 = t->src[0];
  193. const struct ggml_tensor * src1 = t->src[1];
  194. if (ask) {
  195. return true; // Always retrieve data
  196. }
  197. char src1_str[128] = {0};
  198. if (src1) {
  199. snprintf(src1_str, sizeof(src1_str), "%s{%s}", src1->name, ggml_ne_string(src1).c_str());
  200. }
  201. LOG("%s: %24s = (%s) %10s(%s{%s}, %s}) = {%s}\n", __func__,
  202. t->name, ggml_type_name(t->type), ggml_op_desc(t),
  203. src0->name, ggml_ne_string(src0).c_str(),
  204. src1 ? src1_str : "",
  205. ggml_ne_string(t).c_str());
  206. // copy the data from the GPU memory if needed
  207. const bool is_host = ggml_backend_buffer_is_host(t->buffer);
  208. if (!is_host) {
  209. auto n_bytes = ggml_nbytes(t);
  210. cb_data->data.resize(n_bytes);
  211. ggml_backend_tensor_get(t, cb_data->data.data(), 0, n_bytes);
  212. }
  213. if (!ggml_is_quantized(t->type)) {
  214. uint8_t * data = is_host ? (uint8_t *) t->data : cb_data->data.data();
  215. std::string tensor_name(t->name);
  216. if (std::string(tensor_name).substr(0, std::string("post_moe-").size()) == "post_moe-" ||
  217. std::string(tensor_name).substr(0, std::string("state_1d-").size()) == "state_1d-") {
  218. if (cb_data->tensors.count(tensor_name) == 0) {
  219. cb_data->tensors[tensor_name] = 1;
  220. } else {
  221. cb_data->tensors[tensor_name]++;
  222. }
  223. save_tensor(t, data, (tensor_name + "_" + std::to_string(cb_data->tensors[t->name]) + ".bin").c_str());
  224. }
  225. ggml_print_tensor(data, t->type, t->ne, t->nb, 3);
  226. }
  227. return true;
  228. }
  229. int main(int argc, char ** argv) {
  230. common_params params;
  231. g_params = &params;
  232. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_MAIN, print_usage)) {
  233. return 1;
  234. }
  235. // Check if cache statistics printing is enabled
  236. print_cache_stats = params.dump_cache;
  237. common_init();
  238. auto & sparams = params.sampling;
  239. // save choice to use color for later
  240. // (note for later: this is a slightly awkward choice)
  241. console::init(params.simple_io, params.use_color);
  242. atexit([]() { console::cleanup(); });
  243. if (params.embedding) {
  244. LOG_ERR("************\n");
  245. LOG_ERR("%s: please use the 'embedding' tool for embedding calculations\n", __func__);
  246. LOG_ERR("************\n\n");
  247. return 0;
  248. }
  249. if (params.n_ctx != 0 && params.n_ctx < 8) {
  250. LOG_WRN("%s: warning: minimum context size is 8, using minimum size.\n", __func__);
  251. params.n_ctx = 8;
  252. }
  253. if (params.rope_freq_base != 0.0) {
  254. LOG_WRN("%s: warning: changing RoPE frequency base to %g.\n", __func__, params.rope_freq_base);
  255. }
  256. if (params.rope_freq_scale != 0.0) {
  257. LOG_WRN("%s: warning: scaling RoPE frequency by %g.\n", __func__, params.rope_freq_scale);
  258. }
  259. LOG_INF("%s: llama backend init\n", __func__);
  260. llama_backend_init();
  261. llama_numa_init(params.numa);
  262. llama_model * model = nullptr;
  263. llama_context * ctx = nullptr;
  264. common_sampler * smpl = nullptr;
  265. g_model = &model;
  266. g_ctx = &ctx;
  267. g_smpl = &smpl;
  268. std::vector<common_chat_msg> chat_msgs;
  269. // load the model and apply lora adapter, if any
  270. callback_data cb_data;
  271. if (params.n_predict > 0 && params.n_predict < 50) {
  272. // enable debug prints if we print small number of tokens
  273. params.cb_eval = ggml_debug;
  274. params.cb_eval_user_data = &cb_data;
  275. }
  276. LOG_INF("%s: load the model and apply lora adapter, if any\n", __func__);
  277. common_init_result llama_init = common_init_from_params(params);
  278. model = llama_init.model.get();
  279. ctx = llama_init.context.get();
  280. if (model == NULL) {
  281. LOG_ERR("%s: error: unable to load model\n", __func__);
  282. return 1;
  283. }
  284. auto * mem = llama_get_memory(ctx);
  285. const llama_vocab * vocab = llama_model_get_vocab(model);
  286. auto chat_templates = common_chat_templates_init(model, params.chat_template);
  287. LOG_INF("%s: llama threadpool init, n_threads = %d\n", __func__, (int) params.cpuparams.n_threads);
  288. auto * cpu_dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
  289. if (!cpu_dev) {
  290. LOG_ERR("%s: no CPU backend found\n", __func__);
  291. return 1;
  292. }
  293. auto * reg = ggml_backend_dev_backend_reg(cpu_dev);
  294. auto * ggml_threadpool_new_fn = (decltype(ggml_threadpool_new) *) ggml_backend_reg_get_proc_address(reg, "ggml_threadpool_new");
  295. auto * ggml_threadpool_free_fn = (decltype(ggml_threadpool_free) *) ggml_backend_reg_get_proc_address(reg, "ggml_threadpool_free");
  296. struct ggml_threadpool_params tpp_batch =
  297. ggml_threadpool_params_from_cpu_params(params.cpuparams_batch);
  298. struct ggml_threadpool_params tpp =
  299. ggml_threadpool_params_from_cpu_params(params.cpuparams);
  300. set_process_priority(params.cpuparams.priority);
  301. struct ggml_threadpool * threadpool_batch = NULL;
  302. if (!ggml_threadpool_params_match(&tpp, &tpp_batch)) {
  303. threadpool_batch = ggml_threadpool_new_fn(&tpp_batch);
  304. if (!threadpool_batch) {
  305. LOG_ERR("%s: batch threadpool create failed : n_threads %d\n", __func__, tpp_batch.n_threads);
  306. return 1;
  307. }
  308. // Start the non-batch threadpool in the paused state
  309. tpp.paused = true;
  310. }
  311. struct ggml_threadpool * threadpool = ggml_threadpool_new_fn(&tpp);
  312. if (!threadpool) {
  313. LOG_ERR("%s: threadpool create failed : n_threads %d\n", __func__, tpp.n_threads);
  314. return 1;
  315. }
  316. llama_attach_threadpool(ctx, threadpool, threadpool_batch);
  317. const int n_ctx_train = llama_model_n_ctx_train(model);
  318. const int n_ctx = llama_n_ctx(ctx);
  319. if (n_ctx > n_ctx_train) {
  320. LOG_WRN("%s: model was trained on only %d context tokens (%d specified)\n", __func__, n_ctx_train, n_ctx);
  321. }
  322. // auto enable conversation mode if chat template is available
  323. const bool has_chat_template = common_chat_templates_was_explicit(chat_templates.get());
  324. if (params.conversation_mode == COMMON_CONVERSATION_MODE_AUTO) {
  325. if (has_chat_template) {
  326. LOG_INF("%s: chat template is available, enabling conversation mode (disable it with -no-cnv)\n", __func__);
  327. params.conversation_mode = COMMON_CONVERSATION_MODE_ENABLED;
  328. } else {
  329. params.conversation_mode = COMMON_CONVERSATION_MODE_DISABLED;
  330. }
  331. }
  332. // in case user force-activate conversation mode (via -cnv) without proper chat template, we show a warning
  333. if (params.conversation_mode && !has_chat_template) {
  334. LOG_WRN("%s: chat template is not available or is not supported. This may cause the model to output suboptimal responses\n", __func__);
  335. }
  336. // print chat template example in conversation mode
  337. if (params.conversation_mode) {
  338. if (params.enable_chat_template) {
  339. if (!params.prompt.empty() && params.system_prompt.empty()) {
  340. LOG_WRN("*** User-specified prompt will pre-start conversation, did you mean to set --system-prompt (-sys) instead?\n");
  341. }
  342. LOG_INF("%s: chat template example:\n%s\n", __func__, common_chat_format_example(chat_templates.get(), params.use_jinja, params.default_template_kwargs).c_str());
  343. } else {
  344. LOG_INF("%s: in-suffix/prefix is specified, chat template will be disabled\n", __func__);
  345. }
  346. }
  347. // print system information
  348. {
  349. LOG_INF("\n");
  350. LOG_INF("%s\n", common_params_get_system_info(params).c_str());
  351. LOG_INF("\n");
  352. }
  353. std::string path_session = params.path_prompt_cache;
  354. std::vector<llama_token> session_tokens;
  355. if (!path_session.empty()) {
  356. LOG_INF("%s: attempting to load saved session from '%s'\n", __func__, path_session.c_str());
  357. if (!file_exists(path_session)) {
  358. LOG_INF("%s: session file does not exist, will create.\n", __func__);
  359. } else if (file_is_empty(path_session)) {
  360. LOG_INF("%s: The session file is empty. A new session will be initialized.\n", __func__);
  361. } else {
  362. // The file exists and is not empty
  363. session_tokens.resize(n_ctx);
  364. size_t n_token_count_out = 0;
  365. if (!llama_state_load_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.capacity(), &n_token_count_out)) {
  366. LOG_ERR("%s: failed to load session file '%s'\n", __func__, path_session.c_str());
  367. return 1;
  368. }
  369. session_tokens.resize(n_token_count_out);
  370. LOG_INF("%s: loaded a session with prompt size of %d tokens\n", __func__, (int)session_tokens.size());
  371. }
  372. }
  373. const bool add_bos = llama_vocab_get_add_bos(vocab) && !params.use_jinja;
  374. if (!llama_model_has_encoder(model)) {
  375. GGML_ASSERT(!llama_vocab_get_add_eos(vocab));
  376. }
  377. LOG_DBG("n_ctx: %d, add_bos: %d\n", n_ctx, add_bos);
  378. std::vector<llama_token> embd_inp;
  379. bool waiting_for_first_input = false;
  380. auto chat_add_and_format = [&chat_msgs, &chat_templates](const std::string & role, const std::string & content) {
  381. common_chat_msg new_msg;
  382. new_msg.role = role;
  383. new_msg.content = content;
  384. auto formatted = common_chat_format_single(chat_templates.get(), chat_msgs, new_msg, role == "user", g_params->use_jinja);
  385. chat_msgs.push_back(new_msg);
  386. LOG_DBG("formatted: '%s'\n", formatted.c_str());
  387. return formatted;
  388. };
  389. std::string prompt;
  390. {
  391. if (params.conversation_mode && params.enable_chat_template) {
  392. if (!params.system_prompt.empty()) {
  393. // format the system prompt (will use template default if empty)
  394. chat_add_and_format("system", params.system_prompt);
  395. }
  396. if (!params.prompt.empty()) {
  397. // format and append the user prompt
  398. chat_add_and_format("user", params.prompt);
  399. } else {
  400. waiting_for_first_input = true;
  401. }
  402. if (!params.system_prompt.empty() || !params.prompt.empty()) {
  403. common_chat_templates_inputs inputs;
  404. inputs.use_jinja = g_params->use_jinja;
  405. inputs.messages = chat_msgs;
  406. inputs.add_generation_prompt = !params.prompt.empty();
  407. prompt = common_chat_templates_apply(chat_templates.get(), inputs).prompt;
  408. }
  409. } else {
  410. // otherwise use the prompt as is
  411. prompt = params.prompt;
  412. }
  413. if (params.interactive_first || !prompt.empty() || session_tokens.empty()) {
  414. LOG_DBG("tokenize the prompt\n");
  415. embd_inp = common_tokenize(ctx, prompt, true, true);
  416. } else {
  417. LOG_DBG("use session tokens\n");
  418. embd_inp = session_tokens;
  419. }
  420. LOG_DBG("prompt: \"%s\"\n", prompt.c_str());
  421. LOG_DBG("tokens: %s\n", string_from(ctx, embd_inp).c_str());
  422. }
  423. // Should not run without any tokens
  424. if (!waiting_for_first_input && embd_inp.empty()) {
  425. if (add_bos) {
  426. embd_inp.push_back(llama_vocab_bos(vocab));
  427. LOG_WRN("embd_inp was considered empty and bos was added: %s\n", string_from(ctx, embd_inp).c_str());
  428. } else {
  429. LOG_ERR("input is empty\n");
  430. return -1;
  431. }
  432. }
  433. // Tokenize negative prompt
  434. if ((int) embd_inp.size() > n_ctx - 4) {
  435. LOG_ERR("%s: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4);
  436. return 1;
  437. }
  438. // debug message about similarity of saved session, if applicable
  439. size_t n_matching_session_tokens = 0;
  440. if (!session_tokens.empty()) {
  441. for (llama_token id : session_tokens) {
  442. if (n_matching_session_tokens >= embd_inp.size() || id != embd_inp[n_matching_session_tokens]) {
  443. break;
  444. }
  445. n_matching_session_tokens++;
  446. }
  447. if (params.prompt.empty() && n_matching_session_tokens == embd_inp.size()) {
  448. LOG_INF("%s: using full prompt from session file\n", __func__);
  449. } else if (n_matching_session_tokens >= embd_inp.size()) {
  450. LOG_INF("%s: session file has exact match for prompt!\n", __func__);
  451. } else if (n_matching_session_tokens < (embd_inp.size() / 2)) {
  452. LOG_WRN("%s: session file has low similarity to prompt (%zu / %zu tokens); will mostly be reevaluated\n",
  453. __func__, n_matching_session_tokens, embd_inp.size());
  454. } else {
  455. LOG_INF("%s: session file matches %zu / %zu tokens of prompt\n",
  456. __func__, n_matching_session_tokens, embd_inp.size());
  457. }
  458. // remove any "future" tokens that we might have inherited from the previous session
  459. llama_memory_seq_rm(mem, -1, n_matching_session_tokens, -1);
  460. }
  461. LOG_DBG("recalculate the cached logits (check): embd_inp.size() %zu, n_matching_session_tokens %zu, embd_inp.size() %zu, session_tokens.size() %zu\n",
  462. embd_inp.size(), n_matching_session_tokens, embd_inp.size(), session_tokens.size());
  463. // if we will use the cache for the full prompt without reaching the end of the cache, force
  464. // reevaluation of the last token to recalculate the cached logits
  465. if (!embd_inp.empty() && n_matching_session_tokens == embd_inp.size() && session_tokens.size() > embd_inp.size()) {
  466. LOG_DBG("recalculate the cached logits (do): session_tokens.resize( %zu )\n", embd_inp.size() - 1);
  467. session_tokens.resize(embd_inp.size() - 1);
  468. }
  469. // number of tokens to keep when resetting context
  470. if (params.n_keep < 0 || params.n_keep > (int) embd_inp.size()) {
  471. params.n_keep = (int)embd_inp.size();
  472. } else {
  473. params.n_keep += add_bos; // always keep the BOS token
  474. }
  475. if (params.conversation_mode) {
  476. if (params.single_turn && !params.prompt.empty()) {
  477. params.interactive = false;
  478. params.interactive_first = false;
  479. } else {
  480. params.interactive_first = true;
  481. }
  482. }
  483. // enable interactive mode if interactive start is specified
  484. if (params.interactive_first) {
  485. params.interactive = true;
  486. }
  487. if (params.verbose_prompt) {
  488. LOG_INF("%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  489. LOG_INF("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  490. for (int i = 0; i < (int) embd_inp.size(); i++) {
  491. LOG_INF("%6d -> '%s'\n", embd_inp[i], common_token_to_piece(ctx, embd_inp[i]).c_str());
  492. }
  493. if (params.n_keep > add_bos) {
  494. LOG_INF("%s: static prompt based on n_keep: '", __func__);
  495. for (int i = 0; i < params.n_keep; i++) {
  496. LOG_CNT("%s", common_token_to_piece(ctx, embd_inp[i]).c_str());
  497. }
  498. LOG_CNT("'\n");
  499. }
  500. LOG_INF("\n");
  501. }
  502. // ctrl+C handling
  503. {
  504. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  505. struct sigaction sigint_action;
  506. sigint_action.sa_handler = sigint_handler;
  507. sigemptyset (&sigint_action.sa_mask);
  508. sigint_action.sa_flags = 0;
  509. sigaction(SIGINT, &sigint_action, NULL);
  510. #elif defined (_WIN32)
  511. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  512. return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
  513. };
  514. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  515. #endif
  516. }
  517. if (params.interactive) {
  518. LOG_INF("%s: interactive mode on.\n", __func__);
  519. if (!params.antiprompt.empty()) {
  520. for (const auto & antiprompt : params.antiprompt) {
  521. LOG_INF("Reverse prompt: '%s'\n", antiprompt.c_str());
  522. if (params.verbose_prompt) {
  523. auto tmp = common_tokenize(ctx, antiprompt, false, true);
  524. for (int i = 0; i < (int) tmp.size(); i++) {
  525. LOG_INF("%6d -> '%s'\n", tmp[i], common_token_to_piece(ctx, tmp[i]).c_str());
  526. }
  527. }
  528. }
  529. }
  530. if (params.input_prefix_bos) {
  531. LOG_INF("Input prefix with BOS\n");
  532. }
  533. if (!params.input_prefix.empty()) {
  534. LOG_INF("Input prefix: '%s'\n", params.input_prefix.c_str());
  535. if (params.verbose_prompt) {
  536. auto tmp = common_tokenize(ctx, params.input_prefix, true, true);
  537. for (int i = 0; i < (int) tmp.size(); i++) {
  538. LOG_INF("%6d -> '%s'\n", tmp[i], common_token_to_piece(ctx, tmp[i]).c_str());
  539. }
  540. }
  541. }
  542. if (!params.input_suffix.empty()) {
  543. LOG_INF("Input suffix: '%s'\n", params.input_suffix.c_str());
  544. if (params.verbose_prompt) {
  545. auto tmp = common_tokenize(ctx, params.input_suffix, false, true);
  546. for (int i = 0; i < (int) tmp.size(); i++) {
  547. LOG_INF("%6d -> '%s'\n", tmp[i], common_token_to_piece(ctx, tmp[i]).c_str());
  548. }
  549. }
  550. }
  551. }
  552. smpl = common_sampler_init(model, sparams);
  553. if (!smpl) {
  554. LOG_ERR("%s: failed to initialize sampling subsystem\n", __func__);
  555. return 1;
  556. }
  557. LOG_INF("sampler seed: %u\n", common_sampler_get_seed(smpl));
  558. LOG_INF("sampler params: \n%s\n", sparams.print().c_str());
  559. LOG_INF("sampler chain: %s\n", common_sampler_print(smpl).c_str());
  560. LOG_INF("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);
  561. // group-attention state
  562. // number of grouped KV tokens so far (used only if params.grp_attn_n > 1)
  563. int ga_i = 0;
  564. const int ga_n = params.grp_attn_n;
  565. const int ga_w = params.grp_attn_w;
  566. if (ga_n != 1) {
  567. GGML_ASSERT(ga_n > 0 && "grp_attn_n must be positive"); // NOLINT
  568. GGML_ASSERT(ga_w % ga_n == 0 && "grp_attn_w must be a multiple of grp_attn_n"); // NOLINT
  569. //GGML_ASSERT(n_ctx_train % ga_w == 0 && "n_ctx_train must be a multiple of grp_attn_w"); // NOLINT
  570. //GGML_ASSERT(n_ctx >= n_ctx_train * ga_n && "n_ctx must be at least n_ctx_train * grp_attn_n"); // NOLINT
  571. LOG_INF("self-extend: n_ctx_train = %d, grp_attn_n = %d, grp_attn_w = %d\n", n_ctx_train, ga_n, ga_w);
  572. }
  573. LOG_INF("\n");
  574. if (params.interactive) {
  575. const char * control_message;
  576. if (params.multiline_input) {
  577. control_message = " - To return control to the AI, end your input with '\\'.\n"
  578. " - To return control without starting a new line, end your input with '/'.\n";
  579. } else {
  580. control_message = " - Press Return to return control to the AI.\n"
  581. " - To return control without starting a new line, end your input with '/'.\n"
  582. " - If you want to submit another line, end your input with '\\'.\n";
  583. }
  584. LOG_INF("== Running in interactive mode. ==\n");
  585. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  586. LOG_INF( " - Press Ctrl+C to interject at any time.\n");
  587. #endif
  588. LOG_INF( "%s", control_message);
  589. if (params.conversation_mode && params.enable_chat_template && params.system_prompt.empty()) {
  590. LOG_INF( " - Not using system message. To change it, set a different value via -sys PROMPT\n");
  591. }
  592. LOG_INF("\n");
  593. is_interacting = params.interactive_first;
  594. }
  595. bool is_antiprompt = false;
  596. bool input_echo = true;
  597. bool display = true;
  598. bool need_to_save_session = !path_session.empty() && n_matching_session_tokens < embd_inp.size();
  599. int n_past = 0;
  600. int n_remain = params.n_predict;
  601. int n_consumed = 0;
  602. int n_session_consumed = 0;
  603. std::vector<int> input_tokens; g_input_tokens = &input_tokens;
  604. std::vector<int> output_tokens; g_output_tokens = &output_tokens;
  605. std::ostringstream output_ss; g_output_ss = &output_ss;
  606. std::ostringstream assistant_ss; // for storing current assistant message, used in conversation mode
  607. // the first thing we will do is to output the prompt, so set color accordingly
  608. console::set_display(console::prompt);
  609. display = params.display_prompt;
  610. std::vector<llama_token> embd;
  611. // single-token antiprompts
  612. std::vector<llama_token> antiprompt_token;
  613. for (const std::string & antiprompt : params.antiprompt) {
  614. auto ids = ::common_tokenize(ctx, antiprompt, false, true);
  615. if (ids.size() == 1) {
  616. antiprompt_token.push_back(ids[0]);
  617. }
  618. }
  619. if (llama_model_has_encoder(model)) {
  620. int enc_input_size = embd_inp.size();
  621. llama_token * enc_input_buf = embd_inp.data();
  622. if (llama_encode(ctx, llama_batch_get_one(enc_input_buf, enc_input_size))) {
  623. LOG_ERR("%s : failed to eval\n", __func__);
  624. return 1;
  625. }
  626. llama_token decoder_start_token_id = llama_model_decoder_start_token(model);
  627. if (decoder_start_token_id == LLAMA_TOKEN_NULL) {
  628. decoder_start_token_id = llama_vocab_bos(vocab);
  629. }
  630. embd_inp.clear();
  631. embd_inp.push_back(decoder_start_token_id);
  632. }
  633. while ((n_remain != 0 && !is_antiprompt) || params.interactive) {
  634. // predict
  635. if (!embd.empty()) {
  636. // Note: (n_ctx - 4) here is to match the logic for commandline prompt handling via
  637. // --prompt or --file which uses the same value.
  638. int max_embd_size = n_ctx - 4;
  639. // Ensure the input doesn't exceed the context size by truncating embd if necessary.
  640. if ((int) embd.size() > max_embd_size) {
  641. const int skipped_tokens = (int) embd.size() - max_embd_size;
  642. embd.resize(max_embd_size);
  643. console::set_display(console::error);
  644. LOG_WRN("<<input too long: skipped %d token%s>>", skipped_tokens, skipped_tokens != 1 ? "s" : "");
  645. console::set_display(console::reset);
  646. }
  647. if (ga_n == 1) {
  648. // infinite text generation via context shifting
  649. // if we run out of context:
  650. // - take the n_keep first tokens from the original prompt (via n_past)
  651. // - take half of the last (n_ctx - n_keep) tokens and recompute the logits in batches
  652. if (n_past + (int) embd.size() >= n_ctx) {
  653. if (!params.ctx_shift){
  654. LOG_WRN("\n\n%s: context full and context shift is disabled => stopping\n", __func__);
  655. break;
  656. }
  657. if (params.n_predict == -2) {
  658. LOG_WRN("\n\n%s: context full and n_predict == %d => stopping\n", __func__, params.n_predict);
  659. break;
  660. }
  661. const int n_left = n_past - params.n_keep;
  662. const int n_discard = n_left/2;
  663. LOG_DBG("context full, swapping: n_past = %d, n_left = %d, n_ctx = %d, n_keep = %d, n_discard = %d\n",
  664. n_past, n_left, n_ctx, params.n_keep, n_discard);
  665. llama_memory_seq_rm (mem, 0, params.n_keep , params.n_keep + n_discard);
  666. llama_memory_seq_add(mem, 0, params.n_keep + n_discard, n_past, -n_discard);
  667. n_past -= n_discard;
  668. LOG_DBG("after swap: n_past = %d\n", n_past);
  669. LOG_DBG("embd: %s\n", string_from(ctx, embd).c_str());
  670. LOG_DBG("clear session path\n");
  671. path_session.clear();
  672. }
  673. } else {
  674. // context extension via Self-Extend
  675. while (n_past >= ga_i + ga_w) {
  676. const int ib = (ga_n*ga_i)/ga_w;
  677. const int bd = (ga_w/ga_n)*(ga_n - 1);
  678. const int dd = (ga_w/ga_n) - ib*bd - ga_w;
  679. LOG_DBG("\n");
  680. LOG_DBG("shift: [%6d, %6d] + %6d -> [%6d, %6d]\n", ga_i, n_past, ib*bd, ga_i + ib*bd, n_past + ib*bd);
  681. LOG_DBG("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);
  682. LOG_DBG("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);
  683. llama_memory_seq_add(mem, 0, ga_i, n_past, ib*bd);
  684. llama_memory_seq_div(mem, 0, ga_i + ib*bd, ga_i + ib*bd + ga_w, ga_n);
  685. llama_memory_seq_add(mem, 0, ga_i + ib*bd + ga_w, n_past + ib*bd, dd);
  686. n_past -= bd;
  687. ga_i += ga_w/ga_n;
  688. LOG_DBG("\nn_past_old = %d, n_past = %d, ga_i = %d\n\n", n_past + bd, n_past, ga_i);
  689. }
  690. }
  691. // try to reuse a matching prefix from the loaded session instead of re-eval (via n_past)
  692. if (n_session_consumed < (int) session_tokens.size()) {
  693. size_t i = 0;
  694. for ( ; i < embd.size(); i++) {
  695. if (embd[i] != session_tokens[n_session_consumed]) {
  696. session_tokens.resize(n_session_consumed);
  697. break;
  698. }
  699. n_past++;
  700. n_session_consumed++;
  701. if (n_session_consumed >= (int) session_tokens.size()) {
  702. ++i;
  703. break;
  704. }
  705. }
  706. if (i > 0) {
  707. embd.erase(embd.begin(), embd.begin() + i);
  708. }
  709. }
  710. for (int i = 0; i < (int) embd.size(); i += params.n_batch) {
  711. int n_eval = (int) embd.size() - i;
  712. if (n_eval > params.n_batch) {
  713. n_eval = params.n_batch;
  714. }
  715. LOG_DBG("eval: %s\n", string_from(ctx, embd).c_str());
  716. if (llama_decode(ctx, llama_batch_get_one(&embd[i], n_eval))) {
  717. LOG_ERR("%s : failed to eval\n", __func__);
  718. return 1;
  719. }
  720. n_past += n_eval;
  721. LOG_DBG("n_past = %d\n", n_past);
  722. // Display total tokens alongside total time
  723. if (params.n_print > 0 && n_past % params.n_print == 0) {
  724. LOG_DBG("\n\033[31mTokens consumed so far = %d / %d \033[0m\n", n_past, n_ctx);
  725. }
  726. }
  727. if (!embd.empty() && !path_session.empty()) {
  728. session_tokens.insert(session_tokens.end(), embd.begin(), embd.end());
  729. n_session_consumed = session_tokens.size();
  730. }
  731. }
  732. embd.clear();
  733. if ((int) embd_inp.size() <= n_consumed && !is_interacting) {
  734. // optionally save the session on first sample (for faster prompt loading next time)
  735. if (!path_session.empty() && need_to_save_session && !params.prompt_cache_ro) {
  736. need_to_save_session = false;
  737. llama_state_save_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
  738. LOG_DBG("saved session to %s\n", path_session.c_str());
  739. }
  740. const llama_token id = common_sampler_sample(smpl, ctx, -1);
  741. common_sampler_accept(smpl, id, /* accept_grammar= */ true);
  742. // LOG_DBG("last: %s\n", string_from(ctx, smpl->prev.to_vector()).c_str());
  743. embd.push_back(id);
  744. // Print cache statistics after each token generation
  745. token_count++;
  746. // echo this to console
  747. input_echo = true;
  748. // decrement remaining sampling budget
  749. --n_remain;
  750. LOG_DBG("n_remain: %d\n", n_remain);
  751. } else {
  752. // some user input remains from prompt or interaction, forward it to processing
  753. LOG_DBG("embd_inp.size(): %d, n_consumed: %d\n", (int) embd_inp.size(), n_consumed);
  754. while ((int) embd_inp.size() > n_consumed) {
  755. embd.push_back(embd_inp[n_consumed]);
  756. // push the prompt in the sampling context in order to apply repetition penalties later
  757. // for the prompt, we don't apply grammar rules
  758. common_sampler_accept(smpl, embd_inp[n_consumed], /* accept_grammar= */ false);
  759. ++n_consumed;
  760. if ((int) embd.size() >= params.n_batch) {
  761. break;
  762. }
  763. }
  764. }
  765. // display text
  766. if (input_echo && display) {
  767. for (auto id : embd) {
  768. const std::string token_str = common_token_to_piece(ctx, id, params.special);
  769. // Console/Stream Output
  770. LOG("%s", token_str.c_str());
  771. // Record Displayed Tokens To Log
  772. // Note: Generated tokens are created one by one hence this check
  773. if (embd.size() > 1) {
  774. // Incoming Requested Tokens
  775. input_tokens.push_back(id);
  776. } else {
  777. // Outgoing Generated Tokens
  778. output_tokens.push_back(id);
  779. output_ss << token_str;
  780. }
  781. }
  782. }
  783. // reset color to default if there is no pending user input
  784. if (input_echo && (int) embd_inp.size() == n_consumed) {
  785. console::set_display(console::reset);
  786. display = true;
  787. }
  788. // if not currently processing queued inputs;
  789. if ((int) embd_inp.size() <= n_consumed) {
  790. // check for reverse prompt in the last n_prev tokens
  791. if (!params.antiprompt.empty()) {
  792. const int n_prev = 32;
  793. const std::string last_output = common_sampler_prev_str(smpl, ctx, n_prev);
  794. is_antiprompt = false;
  795. // Check if each of the reverse prompts appears at the end of the output.
  796. // If we're not running interactively, the reverse prompt might be tokenized with some following characters
  797. // so we'll compensate for that by widening the search window a bit.
  798. for (std::string & antiprompt : params.antiprompt) {
  799. size_t extra_padding = params.interactive ? 0 : 2;
  800. size_t search_start_pos = last_output.length() > static_cast<size_t>(antiprompt.length() + extra_padding)
  801. ? last_output.length() - static_cast<size_t>(antiprompt.length() + extra_padding)
  802. : 0;
  803. if (last_output.find(antiprompt, search_start_pos) != std::string::npos) {
  804. if (params.interactive) {
  805. is_interacting = true;
  806. }
  807. is_antiprompt = true;
  808. break;
  809. }
  810. }
  811. // check for reverse prompt using special tokens
  812. // avoid calling common_sampler_last() if last_output is empty
  813. if (!last_output.empty()) {
  814. llama_token last_token = common_sampler_last(smpl);
  815. for (auto token : antiprompt_token) {
  816. if (token == last_token) {
  817. if (params.interactive) {
  818. is_interacting = true;
  819. }
  820. is_antiprompt = true;
  821. break;
  822. }
  823. }
  824. }
  825. if (is_antiprompt) {
  826. LOG_DBG("found antiprompt: %s\n", last_output.c_str());
  827. }
  828. }
  829. // deal with end of generation tokens in interactive mode
  830. if (!waiting_for_first_input && llama_vocab_is_eog(vocab, common_sampler_last(smpl))) {
  831. LOG_DBG("found an EOG token\n");
  832. if (params.interactive) {
  833. if (!params.antiprompt.empty()) {
  834. // tokenize and inject first reverse prompt
  835. const auto first_antiprompt = common_tokenize(ctx, params.antiprompt.front(), false, true);
  836. embd_inp.insert(embd_inp.end(), first_antiprompt.begin(), first_antiprompt.end());
  837. is_antiprompt = true;
  838. }
  839. if (params.enable_chat_template) {
  840. chat_add_and_format("assistant", assistant_ss.str());
  841. }
  842. is_interacting = true;
  843. LOG("\n");
  844. }
  845. }
  846. // if current token is not EOG, we add it to current assistant message
  847. if (params.conversation_mode && !waiting_for_first_input) {
  848. const auto id = common_sampler_last(smpl);
  849. assistant_ss << common_token_to_piece(ctx, id, false);
  850. if (!prompt.empty()) {
  851. prompt.clear();
  852. is_interacting = false;
  853. }
  854. }
  855. if ((n_past > 0 || waiting_for_first_input) && is_interacting) {
  856. LOG_DBG("waiting for user input\n");
  857. if (params.conversation_mode) {
  858. LOG("\n> ");
  859. }
  860. if (params.input_prefix_bos) {
  861. LOG_DBG("adding input prefix BOS token\n");
  862. embd_inp.push_back(llama_vocab_bos(vocab));
  863. }
  864. std::string buffer;
  865. if (!params.input_prefix.empty() && !params.conversation_mode) {
  866. LOG_DBG("appending input prefix: '%s'\n", params.input_prefix.c_str());
  867. LOG("%s", params.input_prefix.c_str());
  868. }
  869. // color user input only
  870. console::set_display(console::user_input);
  871. display = params.display_prompt;
  872. std::string line;
  873. bool another_line = true;
  874. do {
  875. another_line = console::readline(line, params.multiline_input);
  876. buffer += line;
  877. } while (another_line);
  878. // done taking input, reset color
  879. console::set_display(console::reset);
  880. display = true;
  881. if (buffer.empty()) { // Ctrl+D on empty line exits
  882. LOG("EOF by user\n");
  883. break;
  884. }
  885. if (buffer.back() == '\n') {
  886. // Implement #587:
  887. // If the user wants the text to end in a newline,
  888. // this should be accomplished by explicitly adding a newline by using \ followed by return,
  889. // then returning control by pressing return again.
  890. buffer.pop_back();
  891. }
  892. if (buffer.empty()) { // Enter key on empty line lets the user pass control back
  893. LOG_DBG("empty line, passing control back\n");
  894. } else { // Add tokens to embd only if the input buffer is non-empty
  895. // append input suffix if any
  896. if (!params.input_suffix.empty() && !params.conversation_mode) {
  897. LOG_DBG("appending input suffix: '%s'\n", params.input_suffix.c_str());
  898. LOG("%s", params.input_suffix.c_str());
  899. }
  900. LOG_DBG("buffer: '%s'\n", buffer.c_str());
  901. const size_t original_size = embd_inp.size();
  902. if (params.escape) {
  903. string_process_escapes(buffer);
  904. }
  905. bool format_chat = params.conversation_mode && params.enable_chat_template;
  906. std::string user_inp = format_chat
  907. ? chat_add_and_format("user", std::move(buffer))
  908. : std::move(buffer);
  909. // TODO: one inconvenient of current chat template implementation is that we can't distinguish between user input and special tokens (prefix/postfix)
  910. const auto line_pfx = common_tokenize(ctx, params.input_prefix, false, true);
  911. const auto line_inp = common_tokenize(ctx, user_inp, false, format_chat);
  912. const auto line_sfx = common_tokenize(ctx, params.input_suffix, false, true);
  913. LOG_DBG("input tokens: %s\n", string_from(ctx, line_inp).c_str());
  914. // if user stop generation mid-way, we must add EOT to finish model's last response
  915. if (need_insert_eot && format_chat) {
  916. llama_token eot = llama_vocab_eot(vocab);
  917. embd_inp.push_back(eot == LLAMA_TOKEN_NULL ? llama_vocab_eos(vocab) : eot);
  918. need_insert_eot = false;
  919. }
  920. embd_inp.insert(embd_inp.end(), line_pfx.begin(), line_pfx.end());
  921. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  922. embd_inp.insert(embd_inp.end(), line_sfx.begin(), line_sfx.end());
  923. if (params.verbose_prompt) {
  924. LOG_INF("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size() - original_size);
  925. }
  926. for (size_t i = original_size; i < embd_inp.size(); ++i) {
  927. const llama_token token = embd_inp[i];
  928. const std::string token_str = common_token_to_piece(ctx, token);
  929. output_tokens.push_back(token);
  930. output_ss << token_str;
  931. if (params.verbose_prompt) {
  932. LOG_INF("%6d -> '%s'\n", token, token_str.c_str());
  933. }
  934. }
  935. // reset assistant message
  936. assistant_ss.str("");
  937. n_remain -= line_inp.size();
  938. LOG_DBG("n_remain: %d\n", n_remain);
  939. }
  940. input_echo = false; // do not echo this again
  941. }
  942. if (n_past > 0 || waiting_for_first_input) {
  943. if (is_interacting) {
  944. common_sampler_reset(smpl);
  945. }
  946. is_interacting = false;
  947. if (waiting_for_first_input && params.single_turn) {
  948. params.interactive = false;
  949. params.interactive_first = false;
  950. }
  951. waiting_for_first_input = false;
  952. }
  953. }
  954. // end of generation
  955. if (!embd.empty() && llama_vocab_is_eog(vocab, embd.back()) && !(params.interactive)) {
  956. LOG(" [end of text]\n");
  957. break;
  958. }
  959. // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
  960. // We skip this logic when n_predict == -1 (infinite) or -2 (stop at context size).
  961. if (params.interactive && n_remain <= 0 && params.n_predict >= 0) {
  962. n_remain = params.n_predict;
  963. is_interacting = true;
  964. }
  965. }
  966. if (!path_session.empty() && params.prompt_cache_all && !params.prompt_cache_ro) {
  967. LOG("\n%s: saving final output to session file '%s'\n", __func__, path_session.c_str());
  968. llama_state_save_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
  969. }
  970. LOG("\n\n");
  971. common_perf_print(ctx, smpl);
  972. common_sampler_free(smpl);
  973. llama_backend_free();
  974. ggml_threadpool_free_fn(threadpool);
  975. ggml_threadpool_free_fn(threadpool_batch);
  976. return 0;
  977. }