main.cpp 47 KB

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