main.cpp 46 KB

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