main.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  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, 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(tensor->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. float 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, (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. // callback_data cb_data;
  267. // params.cb_eval = ggml_debug;
  268. // params.cb_eval_user_data = &cb_data;
  269. LOG_INF("%s: load the model and apply lora adapter, if any\n", __func__);
  270. common_init_result llama_init = common_init_from_params(params);
  271. model = llama_init.model.get();
  272. ctx = llama_init.context.get();
  273. if (model == NULL) {
  274. LOG_ERR("%s: error: unable to load model\n", __func__);
  275. return 1;
  276. }
  277. auto * mem = llama_get_memory(ctx);
  278. const llama_vocab * vocab = llama_model_get_vocab(model);
  279. auto chat_templates = common_chat_templates_init(model, params.chat_template);
  280. LOG_INF("%s: llama threadpool init, n_threads = %d\n", __func__, (int) params.cpuparams.n_threads);
  281. auto * cpu_dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
  282. if (!cpu_dev) {
  283. LOG_ERR("%s: no CPU backend found\n", __func__);
  284. return 1;
  285. }
  286. auto * reg = ggml_backend_dev_backend_reg(cpu_dev);
  287. auto * ggml_threadpool_new_fn = (decltype(ggml_threadpool_new) *) ggml_backend_reg_get_proc_address(reg, "ggml_threadpool_new");
  288. auto * ggml_threadpool_free_fn = (decltype(ggml_threadpool_free) *) ggml_backend_reg_get_proc_address(reg, "ggml_threadpool_free");
  289. struct ggml_threadpool_params tpp_batch =
  290. ggml_threadpool_params_from_cpu_params(params.cpuparams_batch);
  291. struct ggml_threadpool_params tpp =
  292. ggml_threadpool_params_from_cpu_params(params.cpuparams);
  293. set_process_priority(params.cpuparams.priority);
  294. struct ggml_threadpool * threadpool_batch = NULL;
  295. if (!ggml_threadpool_params_match(&tpp, &tpp_batch)) {
  296. threadpool_batch = ggml_threadpool_new_fn(&tpp_batch);
  297. if (!threadpool_batch) {
  298. LOG_ERR("%s: batch threadpool create failed : n_threads %d\n", __func__, tpp_batch.n_threads);
  299. return 1;
  300. }
  301. // Start the non-batch threadpool in the paused state
  302. tpp.paused = true;
  303. }
  304. struct ggml_threadpool * threadpool = ggml_threadpool_new_fn(&tpp);
  305. if (!threadpool) {
  306. LOG_ERR("%s: threadpool create failed : n_threads %d\n", __func__, tpp.n_threads);
  307. return 1;
  308. }
  309. llama_attach_threadpool(ctx, threadpool, threadpool_batch);
  310. const int n_ctx_train = llama_model_n_ctx_train(model);
  311. const int n_ctx = llama_n_ctx(ctx);
  312. if (n_ctx > n_ctx_train) {
  313. LOG_WRN("%s: model was trained on only %d context tokens (%d specified)\n", __func__, n_ctx_train, n_ctx);
  314. }
  315. // auto enable conversation mode if chat template is available
  316. const bool has_chat_template = common_chat_templates_was_explicit(chat_templates.get());
  317. if (params.conversation_mode == COMMON_CONVERSATION_MODE_AUTO) {
  318. if (has_chat_template) {
  319. LOG_INF("%s: chat template is available, enabling conversation mode (disable it with -no-cnv)\n", __func__);
  320. params.conversation_mode = COMMON_CONVERSATION_MODE_ENABLED;
  321. } else {
  322. params.conversation_mode = COMMON_CONVERSATION_MODE_DISABLED;
  323. }
  324. }
  325. // in case user force-activate conversation mode (via -cnv) without proper chat template, we show a warning
  326. if (params.conversation_mode && !has_chat_template) {
  327. LOG_WRN("%s: chat template is not available or is not supported. This may cause the model to output suboptimal responses\n", __func__);
  328. }
  329. // print chat template example in conversation mode
  330. if (params.conversation_mode) {
  331. if (params.enable_chat_template) {
  332. if (!params.prompt.empty() && params.system_prompt.empty()) {
  333. LOG_WRN("*** User-specified prompt will pre-start conversation, did you mean to set --system-prompt (-sys) instead?\n");
  334. }
  335. 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());
  336. } else {
  337. LOG_INF("%s: in-suffix/prefix is specified, chat template will be disabled\n", __func__);
  338. }
  339. }
  340. // print system information
  341. {
  342. LOG_INF("\n");
  343. LOG_INF("%s\n", common_params_get_system_info(params).c_str());
  344. LOG_INF("\n");
  345. }
  346. std::string path_session = params.path_prompt_cache;
  347. std::vector<llama_token> session_tokens;
  348. if (!path_session.empty()) {
  349. LOG_INF("%s: attempting to load saved session from '%s'\n", __func__, path_session.c_str());
  350. if (!file_exists(path_session)) {
  351. LOG_INF("%s: session file does not exist, will create.\n", __func__);
  352. } else if (file_is_empty(path_session)) {
  353. LOG_INF("%s: The session file is empty. A new session will be initialized.\n", __func__);
  354. } else {
  355. // The file exists and is not empty
  356. session_tokens.resize(n_ctx);
  357. size_t n_token_count_out = 0;
  358. if (!llama_state_load_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.capacity(), &n_token_count_out)) {
  359. LOG_ERR("%s: failed to load session file '%s'\n", __func__, path_session.c_str());
  360. return 1;
  361. }
  362. session_tokens.resize(n_token_count_out);
  363. LOG_INF("%s: loaded a session with prompt size of %d tokens\n", __func__, (int)session_tokens.size());
  364. }
  365. }
  366. const bool add_bos = llama_vocab_get_add_bos(vocab) && !params.use_jinja;
  367. if (!llama_model_has_encoder(model)) {
  368. GGML_ASSERT(!llama_vocab_get_add_eos(vocab));
  369. }
  370. LOG_DBG("n_ctx: %d, add_bos: %d\n", n_ctx, add_bos);
  371. std::vector<llama_token> embd_inp;
  372. bool waiting_for_first_input = false;
  373. auto chat_add_and_format = [&chat_msgs, &chat_templates](const std::string & role, const std::string & content) {
  374. common_chat_msg new_msg;
  375. new_msg.role = role;
  376. new_msg.content = content;
  377. auto formatted = common_chat_format_single(chat_templates.get(), chat_msgs, new_msg, role == "user", g_params->use_jinja);
  378. chat_msgs.push_back(new_msg);
  379. LOG_DBG("formatted: '%s'\n", formatted.c_str());
  380. return formatted;
  381. };
  382. std::string prompt;
  383. {
  384. if (params.conversation_mode && params.enable_chat_template) {
  385. if (!params.system_prompt.empty()) {
  386. // format the system prompt (will use template default if empty)
  387. chat_add_and_format("system", params.system_prompt);
  388. }
  389. if (!params.prompt.empty()) {
  390. // format and append the user prompt
  391. chat_add_and_format("user", params.prompt);
  392. } else {
  393. waiting_for_first_input = true;
  394. }
  395. if (!params.system_prompt.empty() || !params.prompt.empty()) {
  396. common_chat_templates_inputs inputs;
  397. inputs.use_jinja = g_params->use_jinja;
  398. inputs.messages = chat_msgs;
  399. inputs.add_generation_prompt = !params.prompt.empty();
  400. prompt = common_chat_templates_apply(chat_templates.get(), inputs).prompt;
  401. }
  402. } else {
  403. // otherwise use the prompt as is
  404. prompt = params.prompt;
  405. }
  406. if (params.interactive_first || !prompt.empty() || session_tokens.empty()) {
  407. LOG_DBG("tokenize the prompt\n");
  408. embd_inp = common_tokenize(ctx, prompt, true, true);
  409. } else {
  410. LOG_DBG("use session tokens\n");
  411. embd_inp = session_tokens;
  412. }
  413. LOG_DBG("prompt: \"%s\"\n", prompt.c_str());
  414. LOG_DBG("tokens: %s\n", string_from(ctx, embd_inp).c_str());
  415. }
  416. // Should not run without any tokens
  417. if (!waiting_for_first_input && embd_inp.empty()) {
  418. if (add_bos) {
  419. embd_inp.push_back(llama_vocab_bos(vocab));
  420. LOG_WRN("embd_inp was considered empty and bos was added: %s\n", string_from(ctx, embd_inp).c_str());
  421. } else {
  422. LOG_ERR("input is empty\n");
  423. return -1;
  424. }
  425. }
  426. // Tokenize negative prompt
  427. if ((int) embd_inp.size() > n_ctx - 4) {
  428. LOG_ERR("%s: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4);
  429. return 1;
  430. }
  431. // debug message about similarity of saved session, if applicable
  432. size_t n_matching_session_tokens = 0;
  433. if (!session_tokens.empty()) {
  434. for (llama_token id : session_tokens) {
  435. if (n_matching_session_tokens >= embd_inp.size() || id != embd_inp[n_matching_session_tokens]) {
  436. break;
  437. }
  438. n_matching_session_tokens++;
  439. }
  440. if (params.prompt.empty() && n_matching_session_tokens == embd_inp.size()) {
  441. LOG_INF("%s: using full prompt from session file\n", __func__);
  442. } else if (n_matching_session_tokens >= embd_inp.size()) {
  443. LOG_INF("%s: session file has exact match for prompt!\n", __func__);
  444. } else if (n_matching_session_tokens < (embd_inp.size() / 2)) {
  445. LOG_WRN("%s: session file has low similarity to prompt (%zu / %zu tokens); will mostly be reevaluated\n",
  446. __func__, n_matching_session_tokens, embd_inp.size());
  447. } else {
  448. LOG_INF("%s: session file matches %zu / %zu tokens of prompt\n",
  449. __func__, n_matching_session_tokens, embd_inp.size());
  450. }
  451. // remove any "future" tokens that we might have inherited from the previous session
  452. llama_memory_seq_rm(mem, -1, n_matching_session_tokens, -1);
  453. }
  454. 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",
  455. embd_inp.size(), n_matching_session_tokens, embd_inp.size(), session_tokens.size());
  456. // if we will use the cache for the full prompt without reaching the end of the cache, force
  457. // reevaluation of the last token to recalculate the cached logits
  458. if (!embd_inp.empty() && n_matching_session_tokens == embd_inp.size() && session_tokens.size() > embd_inp.size()) {
  459. LOG_DBG("recalculate the cached logits (do): session_tokens.resize( %zu )\n", embd_inp.size() - 1);
  460. session_tokens.resize(embd_inp.size() - 1);
  461. }
  462. // number of tokens to keep when resetting context
  463. if (params.n_keep < 0 || params.n_keep > (int) embd_inp.size()) {
  464. params.n_keep = (int)embd_inp.size();
  465. } else {
  466. params.n_keep += add_bos; // always keep the BOS token
  467. }
  468. if (params.conversation_mode) {
  469. if (params.single_turn && !params.prompt.empty()) {
  470. params.interactive = false;
  471. params.interactive_first = false;
  472. } else {
  473. params.interactive_first = true;
  474. }
  475. }
  476. // enable interactive mode if interactive start is specified
  477. if (params.interactive_first) {
  478. params.interactive = true;
  479. }
  480. if (params.verbose_prompt) {
  481. LOG_INF("%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  482. LOG_INF("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  483. for (int i = 0; i < (int) embd_inp.size(); i++) {
  484. LOG_INF("%6d -> '%s'\n", embd_inp[i], common_token_to_piece(ctx, embd_inp[i]).c_str());
  485. }
  486. if (params.n_keep > add_bos) {
  487. LOG_INF("%s: static prompt based on n_keep: '", __func__);
  488. for (int i = 0; i < params.n_keep; i++) {
  489. LOG_CNT("%s", common_token_to_piece(ctx, embd_inp[i]).c_str());
  490. }
  491. LOG_CNT("'\n");
  492. }
  493. LOG_INF("\n");
  494. }
  495. // ctrl+C handling
  496. {
  497. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  498. struct sigaction sigint_action;
  499. sigint_action.sa_handler = sigint_handler;
  500. sigemptyset (&sigint_action.sa_mask);
  501. sigint_action.sa_flags = 0;
  502. sigaction(SIGINT, &sigint_action, NULL);
  503. #elif defined (_WIN32)
  504. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  505. return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
  506. };
  507. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  508. #endif
  509. }
  510. if (params.interactive) {
  511. LOG_INF("%s: interactive mode on.\n", __func__);
  512. if (!params.antiprompt.empty()) {
  513. for (const auto & antiprompt : params.antiprompt) {
  514. LOG_INF("Reverse prompt: '%s'\n", antiprompt.c_str());
  515. if (params.verbose_prompt) {
  516. auto tmp = common_tokenize(ctx, antiprompt, false, true);
  517. for (int i = 0; i < (int) tmp.size(); i++) {
  518. LOG_INF("%6d -> '%s'\n", tmp[i], common_token_to_piece(ctx, tmp[i]).c_str());
  519. }
  520. }
  521. }
  522. }
  523. if (params.input_prefix_bos) {
  524. LOG_INF("Input prefix with BOS\n");
  525. }
  526. if (!params.input_prefix.empty()) {
  527. LOG_INF("Input prefix: '%s'\n", params.input_prefix.c_str());
  528. if (params.verbose_prompt) {
  529. auto tmp = common_tokenize(ctx, params.input_prefix, true, true);
  530. for (int i = 0; i < (int) tmp.size(); i++) {
  531. LOG_INF("%6d -> '%s'\n", tmp[i], common_token_to_piece(ctx, tmp[i]).c_str());
  532. }
  533. }
  534. }
  535. if (!params.input_suffix.empty()) {
  536. LOG_INF("Input suffix: '%s'\n", params.input_suffix.c_str());
  537. if (params.verbose_prompt) {
  538. auto tmp = common_tokenize(ctx, params.input_suffix, false, true);
  539. for (int i = 0; i < (int) tmp.size(); i++) {
  540. LOG_INF("%6d -> '%s'\n", tmp[i], common_token_to_piece(ctx, tmp[i]).c_str());
  541. }
  542. }
  543. }
  544. }
  545. smpl = common_sampler_init(model, sparams);
  546. if (!smpl) {
  547. LOG_ERR("%s: failed to initialize sampling subsystem\n", __func__);
  548. return 1;
  549. }
  550. LOG_INF("sampler seed: %u\n", common_sampler_get_seed(smpl));
  551. LOG_INF("sampler params: \n%s\n", sparams.print().c_str());
  552. LOG_INF("sampler chain: %s\n", common_sampler_print(smpl).c_str());
  553. 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);
  554. // group-attention state
  555. // number of grouped KV tokens so far (used only if params.grp_attn_n > 1)
  556. int ga_i = 0;
  557. const int ga_n = params.grp_attn_n;
  558. const int ga_w = params.grp_attn_w;
  559. if (ga_n != 1) {
  560. GGML_ASSERT(ga_n > 0 && "grp_attn_n must be positive"); // NOLINT
  561. GGML_ASSERT(ga_w % ga_n == 0 && "grp_attn_w must be a multiple of grp_attn_n"); // NOLINT
  562. //GGML_ASSERT(n_ctx_train % ga_w == 0 && "n_ctx_train must be a multiple of grp_attn_w"); // NOLINT
  563. //GGML_ASSERT(n_ctx >= n_ctx_train * ga_n && "n_ctx must be at least n_ctx_train * grp_attn_n"); // NOLINT
  564. LOG_INF("self-extend: n_ctx_train = %d, grp_attn_n = %d, grp_attn_w = %d\n", n_ctx_train, ga_n, ga_w);
  565. }
  566. LOG_INF("\n");
  567. if (params.interactive) {
  568. const char * control_message;
  569. if (params.multiline_input) {
  570. control_message = " - To return control to the AI, end your input with '\\'.\n"
  571. " - To return control without starting a new line, end your input with '/'.\n";
  572. } else {
  573. control_message = " - Press Return to return control to the AI.\n"
  574. " - To return control without starting a new line, end your input with '/'.\n"
  575. " - If you want to submit another line, end your input with '\\'.\n";
  576. }
  577. LOG_INF("== Running in interactive mode. ==\n");
  578. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  579. LOG_INF( " - Press Ctrl+C to interject at any time.\n");
  580. #endif
  581. LOG_INF( "%s", control_message);
  582. if (params.conversation_mode && params.enable_chat_template && params.system_prompt.empty()) {
  583. LOG_INF( " - Not using system message. To change it, set a different value via -sys PROMPT\n");
  584. }
  585. LOG_INF("\n");
  586. is_interacting = params.interactive_first;
  587. }
  588. bool is_antiprompt = false;
  589. bool input_echo = true;
  590. bool display = true;
  591. bool need_to_save_session = !path_session.empty() && n_matching_session_tokens < embd_inp.size();
  592. int n_past = 0;
  593. int n_remain = params.n_predict;
  594. int n_consumed = 0;
  595. int n_session_consumed = 0;
  596. std::vector<int> input_tokens; g_input_tokens = &input_tokens;
  597. std::vector<int> output_tokens; g_output_tokens = &output_tokens;
  598. std::ostringstream output_ss; g_output_ss = &output_ss;
  599. std::ostringstream assistant_ss; // for storing current assistant message, used in conversation mode
  600. // the first thing we will do is to output the prompt, so set color accordingly
  601. console::set_display(console::prompt);
  602. display = params.display_prompt;
  603. std::vector<llama_token> embd;
  604. // single-token antiprompts
  605. std::vector<llama_token> antiprompt_token;
  606. for (const std::string & antiprompt : params.antiprompt) {
  607. auto ids = ::common_tokenize(ctx, antiprompt, false, true);
  608. if (ids.size() == 1) {
  609. antiprompt_token.push_back(ids[0]);
  610. }
  611. }
  612. if (llama_model_has_encoder(model)) {
  613. int enc_input_size = embd_inp.size();
  614. llama_token * enc_input_buf = embd_inp.data();
  615. if (llama_encode(ctx, llama_batch_get_one(enc_input_buf, enc_input_size))) {
  616. LOG_ERR("%s : failed to eval\n", __func__);
  617. return 1;
  618. }
  619. llama_token decoder_start_token_id = llama_model_decoder_start_token(model);
  620. if (decoder_start_token_id == LLAMA_TOKEN_NULL) {
  621. decoder_start_token_id = llama_vocab_bos(vocab);
  622. }
  623. embd_inp.clear();
  624. embd_inp.push_back(decoder_start_token_id);
  625. }
  626. while ((n_remain != 0 && !is_antiprompt) || params.interactive) {
  627. // predict
  628. if (!embd.empty()) {
  629. // Note: (n_ctx - 4) here is to match the logic for commandline prompt handling via
  630. // --prompt or --file which uses the same value.
  631. int max_embd_size = n_ctx - 4;
  632. // Ensure the input doesn't exceed the context size by truncating embd if necessary.
  633. if ((int) embd.size() > max_embd_size) {
  634. const int skipped_tokens = (int) embd.size() - max_embd_size;
  635. embd.resize(max_embd_size);
  636. console::set_display(console::error);
  637. LOG_WRN("<<input too long: skipped %d token%s>>", skipped_tokens, skipped_tokens != 1 ? "s" : "");
  638. console::set_display(console::reset);
  639. }
  640. if (ga_n == 1) {
  641. // infinite text generation via context shifting
  642. // if we run out of context:
  643. // - take the n_keep first tokens from the original prompt (via n_past)
  644. // - take half of the last (n_ctx - n_keep) tokens and recompute the logits in batches
  645. if (n_past + (int) embd.size() >= n_ctx) {
  646. if (!params.ctx_shift){
  647. LOG_WRN("\n\n%s: context full and context shift is disabled => stopping\n", __func__);
  648. break;
  649. }
  650. if (params.n_predict == -2) {
  651. LOG_WRN("\n\n%s: context full and n_predict == %d => stopping\n", __func__, params.n_predict);
  652. break;
  653. }
  654. const int n_left = n_past - params.n_keep;
  655. const int n_discard = n_left/2;
  656. LOG_DBG("context full, swapping: n_past = %d, n_left = %d, n_ctx = %d, n_keep = %d, n_discard = %d\n",
  657. n_past, n_left, n_ctx, params.n_keep, n_discard);
  658. llama_memory_seq_rm (mem, 0, params.n_keep , params.n_keep + n_discard);
  659. llama_memory_seq_add(mem, 0, params.n_keep + n_discard, n_past, -n_discard);
  660. n_past -= n_discard;
  661. LOG_DBG("after swap: n_past = %d\n", n_past);
  662. LOG_DBG("embd: %s\n", string_from(ctx, embd).c_str());
  663. LOG_DBG("clear session path\n");
  664. path_session.clear();
  665. }
  666. } else {
  667. // context extension via Self-Extend
  668. while (n_past >= ga_i + ga_w) {
  669. const int ib = (ga_n*ga_i)/ga_w;
  670. const int bd = (ga_w/ga_n)*(ga_n - 1);
  671. const int dd = (ga_w/ga_n) - ib*bd - ga_w;
  672. LOG_DBG("\n");
  673. LOG_DBG("shift: [%6d, %6d] + %6d -> [%6d, %6d]\n", ga_i, n_past, ib*bd, ga_i + ib*bd, n_past + ib*bd);
  674. 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);
  675. 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);
  676. llama_memory_seq_add(mem, 0, ga_i, n_past, ib*bd);
  677. llama_memory_seq_div(mem, 0, ga_i + ib*bd, ga_i + ib*bd + ga_w, ga_n);
  678. llama_memory_seq_add(mem, 0, ga_i + ib*bd + ga_w, n_past + ib*bd, dd);
  679. n_past -= bd;
  680. ga_i += ga_w/ga_n;
  681. LOG_DBG("\nn_past_old = %d, n_past = %d, ga_i = %d\n\n", n_past + bd, n_past, ga_i);
  682. }
  683. }
  684. // try to reuse a matching prefix from the loaded session instead of re-eval (via n_past)
  685. if (n_session_consumed < (int) session_tokens.size()) {
  686. size_t i = 0;
  687. for ( ; i < embd.size(); i++) {
  688. if (embd[i] != session_tokens[n_session_consumed]) {
  689. session_tokens.resize(n_session_consumed);
  690. break;
  691. }
  692. n_past++;
  693. n_session_consumed++;
  694. if (n_session_consumed >= (int) session_tokens.size()) {
  695. ++i;
  696. break;
  697. }
  698. }
  699. if (i > 0) {
  700. embd.erase(embd.begin(), embd.begin() + i);
  701. }
  702. }
  703. for (int i = 0; i < (int) embd.size(); i += params.n_batch) {
  704. int n_eval = (int) embd.size() - i;
  705. if (n_eval > params.n_batch) {
  706. n_eval = params.n_batch;
  707. }
  708. LOG_DBG("eval: %s\n", string_from(ctx, embd).c_str());
  709. if (llama_decode(ctx, llama_batch_get_one(&embd[i], n_eval))) {
  710. LOG_ERR("%s : failed to eval\n", __func__);
  711. return 1;
  712. }
  713. n_past += n_eval;
  714. LOG_DBG("n_past = %d\n", n_past);
  715. // Display total tokens alongside total time
  716. if (params.n_print > 0 && n_past % params.n_print == 0) {
  717. LOG_DBG("\n\033[31mTokens consumed so far = %d / %d \033[0m\n", n_past, n_ctx);
  718. }
  719. }
  720. if (!embd.empty() && !path_session.empty()) {
  721. session_tokens.insert(session_tokens.end(), embd.begin(), embd.end());
  722. n_session_consumed = session_tokens.size();
  723. }
  724. }
  725. embd.clear();
  726. if ((int) embd_inp.size() <= n_consumed && !is_interacting) {
  727. // optionally save the session on first sample (for faster prompt loading next time)
  728. if (!path_session.empty() && need_to_save_session && !params.prompt_cache_ro) {
  729. need_to_save_session = false;
  730. llama_state_save_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
  731. LOG_DBG("saved session to %s\n", path_session.c_str());
  732. }
  733. const llama_token id = common_sampler_sample(smpl, ctx, -1);
  734. common_sampler_accept(smpl, id, /* accept_grammar= */ true);
  735. // LOG_DBG("last: %s\n", string_from(ctx, smpl->prev.to_vector()).c_str());
  736. embd.push_back(id);
  737. // Print cache statistics after each token generation
  738. token_count++;
  739. // echo this to console
  740. input_echo = true;
  741. // decrement remaining sampling budget
  742. --n_remain;
  743. LOG_DBG("n_remain: %d\n", n_remain);
  744. } else {
  745. // some user input remains from prompt or interaction, forward it to processing
  746. LOG_DBG("embd_inp.size(): %d, n_consumed: %d\n", (int) embd_inp.size(), n_consumed);
  747. while ((int) embd_inp.size() > n_consumed) {
  748. embd.push_back(embd_inp[n_consumed]);
  749. // push the prompt in the sampling context in order to apply repetition penalties later
  750. // for the prompt, we don't apply grammar rules
  751. common_sampler_accept(smpl, embd_inp[n_consumed], /* accept_grammar= */ false);
  752. ++n_consumed;
  753. if ((int) embd.size() >= params.n_batch) {
  754. break;
  755. }
  756. }
  757. }
  758. // display text
  759. if (input_echo && display) {
  760. for (auto id : embd) {
  761. const std::string token_str = common_token_to_piece(ctx, id, params.special);
  762. // Console/Stream Output
  763. LOG("%s", token_str.c_str());
  764. // Record Displayed Tokens To Log
  765. // Note: Generated tokens are created one by one hence this check
  766. if (embd.size() > 1) {
  767. // Incoming Requested Tokens
  768. input_tokens.push_back(id);
  769. } else {
  770. // Outgoing Generated Tokens
  771. output_tokens.push_back(id);
  772. output_ss << token_str;
  773. }
  774. }
  775. }
  776. // reset color to default if there is no pending user input
  777. if (input_echo && (int) embd_inp.size() == n_consumed) {
  778. console::set_display(console::reset);
  779. display = true;
  780. }
  781. // if not currently processing queued inputs;
  782. if ((int) embd_inp.size() <= n_consumed) {
  783. // check for reverse prompt in the last n_prev tokens
  784. if (!params.antiprompt.empty()) {
  785. const int n_prev = 32;
  786. const std::string last_output = common_sampler_prev_str(smpl, ctx, n_prev);
  787. is_antiprompt = false;
  788. // Check if each of the reverse prompts appears at the end of the output.
  789. // If we're not running interactively, the reverse prompt might be tokenized with some following characters
  790. // so we'll compensate for that by widening the search window a bit.
  791. for (std::string & antiprompt : params.antiprompt) {
  792. size_t extra_padding = params.interactive ? 0 : 2;
  793. size_t search_start_pos = last_output.length() > static_cast<size_t>(antiprompt.length() + extra_padding)
  794. ? last_output.length() - static_cast<size_t>(antiprompt.length() + extra_padding)
  795. : 0;
  796. if (last_output.find(antiprompt, search_start_pos) != std::string::npos) {
  797. if (params.interactive) {
  798. is_interacting = true;
  799. }
  800. is_antiprompt = true;
  801. break;
  802. }
  803. }
  804. // check for reverse prompt using special tokens
  805. // avoid calling common_sampler_last() if last_output is empty
  806. if (!last_output.empty()) {
  807. llama_token last_token = common_sampler_last(smpl);
  808. for (auto token : antiprompt_token) {
  809. if (token == last_token) {
  810. if (params.interactive) {
  811. is_interacting = true;
  812. }
  813. is_antiprompt = true;
  814. break;
  815. }
  816. }
  817. }
  818. if (is_antiprompt) {
  819. LOG_DBG("found antiprompt: %s\n", last_output.c_str());
  820. }
  821. }
  822. // deal with end of generation tokens in interactive mode
  823. if (!waiting_for_first_input && llama_vocab_is_eog(vocab, common_sampler_last(smpl))) {
  824. LOG_DBG("found an EOG token\n");
  825. if (params.interactive) {
  826. if (!params.antiprompt.empty()) {
  827. // tokenize and inject first reverse prompt
  828. const auto first_antiprompt = common_tokenize(ctx, params.antiprompt.front(), false, true);
  829. embd_inp.insert(embd_inp.end(), first_antiprompt.begin(), first_antiprompt.end());
  830. is_antiprompt = true;
  831. }
  832. if (params.enable_chat_template) {
  833. chat_add_and_format("assistant", assistant_ss.str());
  834. }
  835. is_interacting = true;
  836. LOG("\n");
  837. }
  838. }
  839. // if current token is not EOG, we add it to current assistant message
  840. if (params.conversation_mode && !waiting_for_first_input) {
  841. const auto id = common_sampler_last(smpl);
  842. assistant_ss << common_token_to_piece(ctx, id, false);
  843. if (!prompt.empty()) {
  844. prompt.clear();
  845. is_interacting = false;
  846. }
  847. }
  848. if ((n_past > 0 || waiting_for_first_input) && is_interacting) {
  849. LOG_DBG("waiting for user input\n");
  850. if (params.conversation_mode) {
  851. LOG("\n> ");
  852. }
  853. if (params.input_prefix_bos) {
  854. LOG_DBG("adding input prefix BOS token\n");
  855. embd_inp.push_back(llama_vocab_bos(vocab));
  856. }
  857. std::string buffer;
  858. if (!params.input_prefix.empty() && !params.conversation_mode) {
  859. LOG_DBG("appending input prefix: '%s'\n", params.input_prefix.c_str());
  860. LOG("%s", params.input_prefix.c_str());
  861. }
  862. // color user input only
  863. console::set_display(console::user_input);
  864. display = params.display_prompt;
  865. std::string line;
  866. bool another_line = true;
  867. do {
  868. another_line = console::readline(line, params.multiline_input);
  869. buffer += line;
  870. } while (another_line);
  871. // done taking input, reset color
  872. console::set_display(console::reset);
  873. display = true;
  874. if (buffer.empty()) { // Ctrl+D on empty line exits
  875. LOG("EOF by user\n");
  876. break;
  877. }
  878. if (buffer.back() == '\n') {
  879. // Implement #587:
  880. // If the user wants the text to end in a newline,
  881. // this should be accomplished by explicitly adding a newline by using \ followed by return,
  882. // then returning control by pressing return again.
  883. buffer.pop_back();
  884. }
  885. if (buffer.empty()) { // Enter key on empty line lets the user pass control back
  886. LOG_DBG("empty line, passing control back\n");
  887. } else { // Add tokens to embd only if the input buffer is non-empty
  888. // append input suffix if any
  889. if (!params.input_suffix.empty() && !params.conversation_mode) {
  890. LOG_DBG("appending input suffix: '%s'\n", params.input_suffix.c_str());
  891. LOG("%s", params.input_suffix.c_str());
  892. }
  893. LOG_DBG("buffer: '%s'\n", buffer.c_str());
  894. const size_t original_size = embd_inp.size();
  895. if (params.escape) {
  896. string_process_escapes(buffer);
  897. }
  898. bool format_chat = params.conversation_mode && params.enable_chat_template;
  899. std::string user_inp = format_chat
  900. ? chat_add_and_format("user", std::move(buffer))
  901. : std::move(buffer);
  902. // TODO: one inconvenient of current chat template implementation is that we can't distinguish between user input and special tokens (prefix/postfix)
  903. const auto line_pfx = common_tokenize(ctx, params.input_prefix, false, true);
  904. const auto line_inp = common_tokenize(ctx, user_inp, false, format_chat);
  905. const auto line_sfx = common_tokenize(ctx, params.input_suffix, false, true);
  906. LOG_DBG("input tokens: %s\n", string_from(ctx, line_inp).c_str());
  907. // if user stop generation mid-way, we must add EOT to finish model's last response
  908. if (need_insert_eot && format_chat) {
  909. llama_token eot = llama_vocab_eot(vocab);
  910. embd_inp.push_back(eot == LLAMA_TOKEN_NULL ? llama_vocab_eos(vocab) : eot);
  911. need_insert_eot = false;
  912. }
  913. embd_inp.insert(embd_inp.end(), line_pfx.begin(), line_pfx.end());
  914. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  915. embd_inp.insert(embd_inp.end(), line_sfx.begin(), line_sfx.end());
  916. if (params.verbose_prompt) {
  917. LOG_INF("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size() - original_size);
  918. }
  919. for (size_t i = original_size; i < embd_inp.size(); ++i) {
  920. const llama_token token = embd_inp[i];
  921. const std::string token_str = common_token_to_piece(ctx, token);
  922. output_tokens.push_back(token);
  923. output_ss << token_str;
  924. if (params.verbose_prompt) {
  925. LOG_INF("%6d -> '%s'\n", token, token_str.c_str());
  926. }
  927. }
  928. // reset assistant message
  929. assistant_ss.str("");
  930. n_remain -= line_inp.size();
  931. LOG_DBG("n_remain: %d\n", n_remain);
  932. }
  933. input_echo = false; // do not echo this again
  934. }
  935. if (n_past > 0 || waiting_for_first_input) {
  936. if (is_interacting) {
  937. common_sampler_reset(smpl);
  938. }
  939. is_interacting = false;
  940. if (waiting_for_first_input && params.single_turn) {
  941. params.interactive = false;
  942. params.interactive_first = false;
  943. }
  944. waiting_for_first_input = false;
  945. }
  946. }
  947. // end of generation
  948. if (!embd.empty() && llama_vocab_is_eog(vocab, embd.back()) && !(params.interactive)) {
  949. LOG(" [end of text]\n");
  950. break;
  951. }
  952. // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
  953. // We skip this logic when n_predict == -1 (infinite) or -2 (stop at context size).
  954. if (params.interactive && n_remain <= 0 && params.n_predict >= 0) {
  955. n_remain = params.n_predict;
  956. is_interacting = true;
  957. }
  958. }
  959. if (!path_session.empty() && params.prompt_cache_all && !params.prompt_cache_ro) {
  960. LOG("\n%s: saving final output to session file '%s'\n", __func__, path_session.c_str());
  961. llama_state_save_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
  962. }
  963. LOG("\n\n");
  964. common_perf_print(ctx, smpl);
  965. common_sampler_free(smpl);
  966. llama_backend_free();
  967. ggml_threadpool_free_fn(threadpool);
  968. ggml_threadpool_free_fn(threadpool_batch);
  969. return 0;
  970. }