Team Ai
Datasetpublic

Brunobkr/llama.cpp_AlgMor24_github

ΩFFFΣLLIa • llama.cpp • AlgMor24 ██████╗ ███████╗███████╗███████╗██╗ ██╗ ██╗ █████╗ ██╔═══██╗██╔════╝██╔════╝██╔════╝██║ ██║ ██║██╔══██╗ ██║ ██║█████╗ █████╗ █████╗ ██║ ██║ ██║███████║ ██║ ██║██╔══╝ ██╔══╝ ██╔══╝ ██║ ██║ ██║██╔══██║ ╚██████╔╝██║ ██║ ███████╗███████╗███████╗██║██║ ██║ ╚═════╝ ╚═╝ ╚═╝ ╚══════╝╚══════╝╚══════╝╚═╝╚═╝ ╚═╝ High-Performance LLM / VLM Inference & Autonomous Agentic Ecosystem… See the full description on the dataset page: https://huggingface.co/datasets/Brunobkr/llama.cpp_AlgMor24_github.

sourceHugging Faceupdated 2mo agoView on Hugging Face
0likes3.1kdownloads
completion.cpp1001 linesDownload Raw Back to completion
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 9#include <clocale>10#include <cstdio>11#include <cstring>12#include <ctime>13#include <fstream>14#include <iostream>15#include <sstream>16#include <string>17#include <vector>18 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_MEAN24#ifndef NOMINMAX25#define NOMINMAX26#endif27#include <windows.h>28#include <signal.h>29#endif30 31#if defined(_MSC_VER)32#pragma warning(disable: 4244 4267) // possible loss of data33#endif34 35static llama_context           ** g_ctx;36static common_sampler          ** g_smpl;37static common_params            * g_params;38static bool is_interacting  = false;39static bool need_insert_eot = false;40 41static void print_usage(int argc, char ** argv) {42    (void) argc;43 44    LOG("\nexample usage:\n");45    LOG("\n  text generation:     %s -m your_model.gguf -p \"I believe the meaning of life is\" -n 128 -no-cnv\n", argv[0]);46    LOG("\n  chat (conversation): %s -m your_model.gguf -sys \"You are a helpful assistant\"\n", argv[0]);47    LOG("\n");48}49 50static bool file_exists(const std::string & path) {51    std::ifstream f(path.c_str());52    return f.good();53}54 55static 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 62#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)63static 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 73            // make sure all logs are flushed74            LOG("Interrupted by user\n");75            common_log_pause(common_log_main());76 77            _exit(130);78        }79    }80}81#endif82 83// satisfies -Wmissing-declarations84int llama_completion(int argc, char ** argv);85 86int llama_completion(int argc, char ** argv) {87    std::setlocale(LC_NUMERIC, "C");88 89    common_params params;90    g_params = &params;91 92    common_init();93 94    if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_COMPLETION, print_usage)) {95        return 1;96    }97 98    auto & sparams = params.sampling;99 100    // save choice to use color for later101    // (note for later: this is a slightly awkward choice)102    console::init(params.simple_io, params.use_color);103    atexit([]() { console::cleanup(); });104 105    if (params.embedding) {106        LOG_ERR("************\n");107        LOG_ERR("%s: please use the 'embedding' tool for embedding calculations\n", __func__);108        LOG_ERR("************\n\n");109 110        return 0;111    }112 113    if (params.n_ctx != 0 && params.n_ctx < 8) {114        LOG_WRN("%s: warning: minimum context size is 8, using minimum size.\n", __func__);115        params.n_ctx = 8;116    }117 118    if (params.rope_freq_base != 0.0) {119        LOG_WRN("%s: warning: changing RoPE frequency base to %g.\n", __func__, params.rope_freq_base);120    }121 122    if (params.rope_freq_scale != 0.0) {123        LOG_WRN("%s: warning: scaling RoPE frequency by %g.\n", __func__, params.rope_freq_scale);124    }125 126    LOG_INF("%s: llama backend init\n", __func__);127 128    llama_backend_init();129    llama_numa_init(params.numa);130 131    llama_model * model = nullptr;132    llama_context * ctx = nullptr;133    common_sampler * smpl = nullptr;134 135    g_ctx = &ctx;136    g_smpl = &smpl;137 138    std::vector<common_chat_msg> chat_msgs;139 140    // load the model and apply lora adapter, if any141    LOG_INF("%s: load the model and apply lora adapter, if any\n", __func__);142 143    auto llama_init = common_init_from_params(params);144 145    ctx   = llama_init->context();146    model = llama_init->model();147    smpl  = llama_init->sampler(0);148 149    if (ctx == NULL) {150        LOG_ERR("%s: error: unable to create context\n", __func__);151        return 1;152    }153 154    llama_memory_t mem = llama_get_memory(ctx);155    const llama_vocab * vocab = llama_model_get_vocab(model);156 157    // note: the time for chat template initialization is not negligible:158    auto chat_templates = common_chat_templates_init(model, params.chat_template);159 160    // start measuring performance timings from here161    llama_perf_context_reset(ctx);162 163    LOG_INF("%s: llama threadpool init, n_threads = %d\n", __func__, (int) params.cpuparams.n_threads);164 165    auto * cpu_dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);166    if (!cpu_dev) {167        LOG_ERR("%s: no CPU backend found\n", __func__);168        return 1;169    }170    auto * reg = ggml_backend_dev_backend_reg(cpu_dev);171    auto * ggml_threadpool_new_fn = (decltype(ggml_threadpool_new) *) ggml_backend_reg_get_proc_address(reg, "ggml_threadpool_new");172    auto * ggml_threadpool_free_fn = (decltype(ggml_threadpool_free) *) ggml_backend_reg_get_proc_address(reg, "ggml_threadpool_free");173 174    struct ggml_threadpool_params tpp_batch =175            ggml_threadpool_params_from_cpu_params(params.cpuparams_batch);176    struct ggml_threadpool_params tpp =177            ggml_threadpool_params_from_cpu_params(params.cpuparams);178 179    if (!set_process_priority(params.cpuparams.priority)) {180        LOG_ERR("%s: error: failed to set process priority\n", __func__);181        return 1;182    }183 184    struct ggml_threadpool * threadpool_batch = NULL;185    if (!ggml_threadpool_params_match(&tpp, &tpp_batch)) {186        threadpool_batch = ggml_threadpool_new_fn(&tpp_batch);187        if (!threadpool_batch) {188            LOG_ERR("%s: batch threadpool create failed : n_threads %d\n", __func__, tpp_batch.n_threads);189            return 1;190        }191 192        // start the non-batch threadpool in the paused state193        tpp.paused = true;194    }195 196    struct ggml_threadpool * threadpool = ggml_threadpool_new_fn(&tpp);197    if (!threadpool) {198        LOG_ERR("%s: threadpool create failed : n_threads %d\n", __func__, tpp.n_threads);199        return 1;200    }201 202    llama_attach_threadpool(ctx, threadpool, threadpool_batch);203 204    const int n_ctx_train = llama_model_n_ctx_train(model);205    const int n_ctx = llama_n_ctx(ctx);206 207    if (n_ctx > n_ctx_train) {208        LOG_WRN("%s: model was trained on only %d context tokens (%d specified)\n", __func__, n_ctx_train, n_ctx);209    }210 211    // auto enable conversation mode if chat template is available212    const bool has_chat_template = common_chat_templates_was_explicit(chat_templates.get());213    if (params.conversation_mode == COMMON_CONVERSATION_MODE_AUTO) {214        if (has_chat_template) {215            LOG_INF("%s: chat template is available, enabling conversation mode (disable it with -no-cnv)\n", __func__);216            params.conversation_mode = COMMON_CONVERSATION_MODE_ENABLED;217        } else {218            params.conversation_mode = COMMON_CONVERSATION_MODE_DISABLED;219        }220    }221 222    // in case user force-activate conversation mode (via -cnv) without proper chat template, we show a warning223    if (params.conversation_mode && !has_chat_template) {224        LOG_WRN("%s: chat template is not available or is not supported. This may cause the model to output suboptimal responses\n", __func__);225    }226 227    // print chat template example in conversation mode228    if (params.conversation_mode) {229        if (params.enable_chat_template) {230            if (!params.prompt.empty() && params.system_prompt.empty()) {231                LOG_WRN("*** User-specified prompt will pre-start conversation, did you mean to set --system-prompt (-sys) instead?\n");232            }233 234            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());235        } else {236            LOG_INF("%s: in-suffix/prefix is specified, chat template will be disabled\n", __func__);237        }238    }239 240    // print system information241    {242        LOG_INF("\n");243        LOG_INF("%s\n", common_params_get_system_info(params).c_str());244        LOG_INF("\n");245    }246 247    std::string path_session = params.path_prompt_cache;248    std::vector<llama_token> session_tokens;249 250    if (!path_session.empty()) {251        LOG_INF("%s: attempting to load saved session from '%s'\n", __func__, path_session.c_str());252        if (!file_exists(path_session)) {253            LOG_INF("%s: session file does not exist, will create.\n", __func__);254        } else if (file_is_empty(path_session)) {255            LOG_INF("%s: The session file is empty. A new session will be initialized.\n", __func__);256        } else {257            // The file exists and is not empty258            session_tokens.resize(n_ctx);259            size_t n_token_count_out = 0;260            if (!llama_state_load_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.capacity(), &n_token_count_out)) {261                LOG_ERR("%s: failed to load session file '%s'\n", __func__, path_session.c_str());262                return 1;263            }264            session_tokens.resize(n_token_count_out);265            LOG_INF("%s: loaded a session with prompt size of %d tokens\n", __func__, (int)session_tokens.size());266        }267    }268 269    const bool add_bos = llama_vocab_get_add_bos(vocab) && !params.use_jinja;270    if (!llama_model_has_encoder(model)) {271        GGML_ASSERT(!llama_vocab_get_add_eos(vocab));272    }273 274    LOG_DBG("n_ctx: %d, add_bos: %d\n", n_ctx, add_bos);275 276    std::vector<llama_token> embd_inp;277 278    bool waiting_for_first_input = false;279    auto chat_add_and_format = [&chat_msgs, &chat_templates](const std::string & role, const std::string & content) {280        common_chat_msg new_msg;281        new_msg.role = role;282        new_msg.content = content;283        auto formatted = common_chat_format_single(chat_templates.get(), chat_msgs, new_msg, role == "user", g_params->use_jinja);284        chat_msgs.push_back(new_msg);285        LOG_DBG("formatted: '%s'\n", formatted.c_str());286        return formatted;287    };288 289    std::string prompt;290    {291        if (params.conversation_mode && params.enable_chat_template) {292            if (!params.system_prompt.empty()) {293                // format the system prompt (will use template default if empty)294                chat_add_and_format("system", params.system_prompt);295            }296 297            if (!params.prompt.empty()) {298                // format and append the user prompt299                chat_add_and_format("user", params.prompt);300            } else {301                waiting_for_first_input = true;302            }303 304            if (!params.system_prompt.empty() || !params.prompt.empty()) {305                common_chat_templates_inputs inputs;306                inputs.use_jinja = g_params->use_jinja;307                inputs.messages = chat_msgs;308                inputs.add_generation_prompt = !params.prompt.empty();309                inputs.force_pure_content = params.force_pure_content_parser;310 311                prompt = common_chat_templates_apply(chat_templates.get(), inputs).prompt;312            }313        } else {314            // otherwise use the prompt as is315            prompt = params.prompt;316        }317 318        if (params.interactive_first || !prompt.empty() || session_tokens.empty()) {319            LOG_DBG("tokenize the prompt\n");320            embd_inp = common_tokenize(ctx, prompt, true, true);321        } else {322            LOG_DBG("use session tokens\n");323            embd_inp = session_tokens;324        }325 326        LOG_DBG("prompt: \"%s\"\n", prompt.c_str());327        LOG_DBG("tokens: %s\n", string_from(ctx, embd_inp).c_str());328    }329 330    // Should not run without any tokens331    if (!waiting_for_first_input && embd_inp.empty()) {332        if (add_bos) {333            embd_inp.push_back(llama_vocab_bos(vocab));334            LOG_WRN("embd_inp was considered empty and bos was added: %s\n", string_from(ctx, embd_inp).c_str());335        } else {336            LOG_ERR("input is empty\n");337            return -1;338        }339    }340 341    // Tokenize negative prompt342    if ((int) embd_inp.size() > n_ctx - 4) {343        LOG_ERR("%s: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4);344        return 1;345    }346 347    bool session_do_save = false;348 349    {350        size_t n_match = 0;351 352        if (!session_tokens.empty()) {353            for (llama_token id : session_tokens) {354                if (n_match >= embd_inp.size() || id != embd_inp[n_match]) {355                    break;356                }357                n_match++;358            }359            if (params.prompt.empty() && n_match == embd_inp.size()) {360                LOG_INF("%s: using full prompt from session file\n", __func__);361            } else if (n_match >= embd_inp.size()) {362                LOG_INF("%s: session file has exact match for prompt!\n", __func__);363            } else if (n_match < (embd_inp.size() / 2)) {364                LOG_WRN("%s: session file has low similarity to prompt (%zu / %zu tokens); will mostly be reevaluated\n",365                        __func__, n_match, embd_inp.size());366            } else {367                LOG_INF("%s: session file matches %zu / %zu tokens of prompt\n",368                        __func__, n_match, embd_inp.size());369            }370 371            // remove any "future" tokens that we might have inherited from the previous session372            if (session_tokens.size() > n_match) {373                llama_pos pos = n_match > 0 ? (llama_pos)(n_match - 1) : 0;374                if (!llama_memory_seq_rm(mem, -1, pos, -1)) {375                    LOG_WRN("%s: unable to reuse common prefix (for example, when the memory is recurrent)\n", __func__);376                    llama_memory_clear(mem, true);377                    session_tokens.clear();378                    n_match = 0;379                } else {380                    session_tokens.resize(n_match);381                }382            }383        }384 385        session_do_save = !path_session.empty() && n_match < embd_inp.size() && !params.prompt_cache_ro;386 387        // Logits are not stored as part of the session state so we need to388        // "replay" the last token to get logits for sampling.389        if (!session_tokens.empty() && n_match > 0 && n_match == session_tokens.size()) {390            if (!common_replay_last_token(ctx, session_tokens.back(), n_match - 1)) {391                return 1;392            }393 394            session_do_save = false;395            LOG_INF("%s: replayed last token from session\n", __func__);396        }397    }398 399    // number of tokens to keep when resetting context400    if (params.n_keep < 0 || params.n_keep > (int) embd_inp.size()) {401        params.n_keep = (int)embd_inp.size();402    } else {403        params.n_keep += add_bos; // always keep the BOS token404    }405 406    if (params.conversation_mode) {407        if (params.single_turn && !params.prompt.empty()) {408            params.interactive = false;409            params.interactive_first = false;410        } else {411            params.interactive_first = true;412        }413    }414 415    // enable interactive mode if interactive start is specified416    if (params.interactive_first) {417        params.interactive = true;418    }419 420    if (params.verbose_prompt) {421        LOG_INF("%s: prompt: '%s'\n", __func__, params.prompt.c_str());422        LOG_INF("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());423        for (int i = 0; i < (int) embd_inp.size(); i++) {424            LOG_INF("%6d -> '%s'\n", embd_inp[i], common_token_to_piece(ctx, embd_inp[i]).c_str());425        }426 427        if (params.n_keep > add_bos) {428            LOG_INF("%s: static prompt based on n_keep: '", __func__);429            for (int i = 0; i < params.n_keep; i++) {430                LOG_CNT("%s", common_token_to_piece(ctx, embd_inp[i]).c_str());431            }432            LOG_CNT("'\n");433        }434        LOG_INF("\n");435    }436 437    // ctrl+C handling438    {439#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))440        struct sigaction sigint_action;441        sigint_action.sa_handler = sigint_handler;442        sigemptyset (&sigint_action.sa_mask);443        sigint_action.sa_flags = 0;444        sigaction(SIGINT, &sigint_action, NULL);445#elif defined (_WIN32)446        auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {447            return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;448        };449        SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);450#endif451    }452 453    if (params.interactive) {454        LOG_INF("%s: interactive mode on.\n", __func__);455 456        if (!params.antiprompt.empty()) {457            for (const auto & antiprompt : params.antiprompt) {458                LOG_INF("Reverse prompt: '%s'\n", antiprompt.c_str());459                if (params.verbose_prompt) {460                    auto tmp = common_tokenize(ctx, antiprompt, false, true);461                    for (int i = 0; i < (int) tmp.size(); i++) {462                        LOG_INF("%6d -> '%s'\n", tmp[i], common_token_to_piece(ctx, tmp[i]).c_str());463                    }464                }465            }466        }467 468        if (params.input_prefix_bos) {469            LOG_INF("Input prefix with BOS\n");470        }471 472        if (!params.input_prefix.empty()) {473            LOG_INF("Input prefix: '%s'\n", params.input_prefix.c_str());474            if (params.verbose_prompt) {475                auto tmp = common_tokenize(ctx, params.input_prefix, true, true);476                for (int i = 0; i < (int) tmp.size(); i++) {477                    LOG_INF("%6d -> '%s'\n", tmp[i], common_token_to_piece(ctx, tmp[i]).c_str());478                }479            }480        }481 482        if (!params.input_suffix.empty()) {483            LOG_INF("Input suffix: '%s'\n", params.input_suffix.c_str());484            if (params.verbose_prompt) {485                auto tmp = common_tokenize(ctx, params.input_suffix, false, true);486                for (int i = 0; i < (int) tmp.size(); i++) {487                    LOG_INF("%6d -> '%s'\n", tmp[i], common_token_to_piece(ctx, tmp[i]).c_str());488                }489            }490        }491    }492 493    LOG_INF("sampler seed: %u\n",     common_sampler_get_seed(smpl));494    LOG_INF("sampler params: \n%s\n", sparams.print().c_str());495    LOG_INF("sampler chain: %s\n",    common_sampler_print(smpl).c_str());496 497    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);498 499    // group-attention state500    // number of grouped KV tokens so far (used only if params.grp_attn_n > 1)501    int ga_i = 0;502 503    const int ga_n = params.grp_attn_n;504    const int ga_w = params.grp_attn_w;505 506    if (ga_n != 1) {507        GGML_ASSERT(ga_n > 0                    && "grp_attn_n must be positive");                     // NOLINT508        GGML_ASSERT(ga_w % ga_n == 0            && "grp_attn_w must be a multiple of grp_attn_n");     // NOLINT509      //GGML_ASSERT(n_ctx_train % ga_w == 0     && "n_ctx_train must be a multiple of grp_attn_w");    // NOLINT510      //GGML_ASSERT(n_ctx >= n_ctx_train * ga_n && "n_ctx must be at least n_ctx_train * grp_attn_n"); // NOLINT511        LOG_INF("self-extend: n_ctx_train = %d, grp_attn_n = %d, grp_attn_w = %d\n", n_ctx_train, ga_n, ga_w);512    }513    LOG_INF("\n");514 515    if (params.interactive) {516        const char * control_message;517        if (params.multiline_input) {518            control_message = " - To return control to the AI, end your input with '\\'.\n"519                              " - To return control without starting a new line, end your input with '/'.\n";520        } else {521            control_message = " - Press Return to return control to the AI.\n"522                              " - To return control without starting a new line, end your input with '/'.\n"523                              " - If you want to submit another line, end your input with '\\'.\n";524        }525        LOG_INF("== Running in interactive mode. ==\n");526#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)527        LOG_INF(       " - Press Ctrl+C to interject at any time.\n");528#endif529        LOG_INF(       "%s", control_message);530        if (params.conversation_mode && params.enable_chat_template && params.system_prompt.empty()) {531            LOG_INF(   " - Not using system message. To change it, set a different value via -sys PROMPT\n");532        }533        LOG_INF("\n");534 535        is_interacting = params.interactive_first;536    }537 538    bool is_antiprompt = false;539    bool input_echo    = true;540    bool display       = true;541 542    int n_past             = 0;543    int n_remain           = params.n_predict;544    int n_consumed         = 0;545    int n_session_consumed = 0;546 547    std::vector<int>   input_tokens;548    std::vector<int>   output_tokens;549    std::ostringstream output_ss;550    std::ostringstream assistant_ss; // for storing current assistant message, used in conversation mode551 552    // the first thing we will do is to output the prompt, so set color accordingly553    console::set_display(DISPLAY_TYPE_PROMPT);554    display = params.display_prompt;555 556    std::vector<llama_token> embd;557 558    // single-token antiprompts559    std::vector<llama_token> antiprompt_token;560 561    for (const std::string & antiprompt : params.antiprompt) {562        auto ids = ::common_tokenize(ctx, antiprompt, false, true);563        if (ids.size() == 1) {564            antiprompt_token.push_back(ids[0]);565        }566    }567 568    if (llama_model_has_encoder(model)) {569        int enc_input_size = embd_inp.size();570        llama_token * enc_input_buf = embd_inp.data();571 572        if (llama_encode(ctx, llama_batch_get_one(enc_input_buf, enc_input_size))) {573            LOG_ERR("%s : failed to eval\n", __func__);574            return 1;575        }576 577        llama_token decoder_start_token_id = llama_model_decoder_start_token(model);578        if (decoder_start_token_id == LLAMA_TOKEN_NULL) {579            decoder_start_token_id = llama_vocab_bos(vocab);580        }581 582        embd_inp.clear();583        embd_inp.push_back(decoder_start_token_id);584    }585 586    while ((n_remain != 0 && !is_antiprompt) || params.interactive) {587        // predict588        if (!embd.empty()) {589            // Note: (n_ctx - 4) here is to match the logic for commandline prompt handling via590            // --prompt or --file which uses the same value.591            int max_embd_size = n_ctx - 4;592 593            // Ensure the input doesn't exceed the context size by truncating embd if necessary.594            if ((int) embd.size() > max_embd_size) {595                const int skipped_tokens = (int) embd.size() - max_embd_size;596                embd.resize(max_embd_size);597 598                console::set_display(DISPLAY_TYPE_ERROR);599                LOG_WRN("<<input too long: skipped %d token%s>>", skipped_tokens, skipped_tokens != 1 ? "s" : "");600                console::set_display(DISPLAY_TYPE_RESET);601            }602 603            if (ga_n == 1) {604                // infinite text generation via context shifting605                // if we run out of context:606                // - take the n_keep first tokens from the original prompt (via n_past)607                // - take half of the last (n_ctx - n_keep) tokens and recompute the logits in batches608 609                if (n_past + (int) embd.size() >= n_ctx) {610                    if (!params.ctx_shift){611                        LOG_WRN("\n\n%s: context full and context shift is disabled => stopping\n", __func__);612                        break;613                    }614 615                    if (params.n_predict == -2) {616                        LOG_WRN("\n\n%s: context full and n_predict == %d => stopping\n", __func__, params.n_predict);617                        break;618                    }619 620                    const int n_left    = n_past - params.n_keep;621                    const int n_discard = n_left/2;622 623                    LOG_DBG("context full, swapping: n_past = %d, n_left = %d, n_ctx = %d, n_keep = %d, n_discard = %d\n",624                            n_past, n_left, n_ctx, params.n_keep, n_discard);625 626                    llama_memory_seq_rm (mem, 0, params.n_keep            , params.n_keep + n_discard);627                    llama_memory_seq_add(mem, 0, params.n_keep + n_discard, n_past, -n_discard);628 629                    n_past -= n_discard;630 631                    LOG_DBG("after swap: n_past = %d\n", n_past);632 633                    LOG_DBG("embd: %s\n", string_from(ctx, embd).c_str());634 635                    LOG_DBG("clear session path\n");636                    path_session.clear();637                }638            } else {639                // context extension via Self-Extend640                while (n_past >= ga_i + ga_w) {641                    const int ib = (ga_n*ga_i)/ga_w;642                    const int bd = (ga_w/ga_n)*(ga_n - 1);643                    const int dd = (ga_w/ga_n) - ib*bd - ga_w;644 645                    LOG_DBG("\n");646                    LOG_DBG("shift: [%6d, %6d] + %6d -> [%6d, %6d]\n", ga_i, n_past, ib*bd, ga_i + ib*bd, n_past + ib*bd);647                    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);648                    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);649 650                    llama_memory_seq_add(mem, 0, ga_i,                n_past,              ib*bd);651                    llama_memory_seq_div(mem, 0, ga_i + ib*bd,        ga_i + ib*bd + ga_w, ga_n);652                    llama_memory_seq_add(mem, 0, ga_i + ib*bd + ga_w, n_past + ib*bd,      dd);653 654                    n_past -= bd;655 656                    ga_i += ga_w/ga_n;657 658                    LOG_DBG("\nn_past_old = %d, n_past = %d, ga_i = %d\n\n", n_past + bd, n_past, ga_i);659                }660            }661 662            // try to reuse a matching prefix from the loaded session instead of re-eval (via n_past)663            if (n_session_consumed < (int) session_tokens.size()) {664                size_t i = 0;665                for ( ; i < embd.size(); i++) {666                    if (embd[i] != session_tokens[n_session_consumed]) {667                        session_tokens.resize(n_session_consumed);668                        break;669                    }670 671                    n_past++;672                    n_session_consumed++;673 674                    if (n_session_consumed >= (int) session_tokens.size()) {675                        ++i;676                        break;677                    }678                }679                if (i > 0) {680                    embd.erase(embd.begin(), embd.begin() + i);681                }682            }683 684            if (!embd.empty()) {685                const bool is_last_batch = (n_consumed >= (int) embd_inp.size());686                const bool save_now = session_do_save && is_last_batch;687                session_tokens.insert(session_tokens.end(), embd.begin(), embd.end());688                if (!common_prompt_batch_decode(ctx, session_tokens, embd.size(), n_past, params.n_batch, path_session, save_now)) {689                    return 1;690                }691                n_session_consumed += embd.size();692                if (save_now) {693                    session_do_save = false;694                }695 696                LOG_DBG("n_past = %d\n", n_past);697 698                // Display total tokens alongside total time699                if (params.n_print > 0 && n_past % params.n_print == 0) {700                    LOG_DBG("\n\033[31mTokens consumed so far = %d / %d \033[0m\n", n_past, n_ctx);701                }702            }703        }704 705        embd.clear();706 707        if ((int) embd_inp.size() <= n_consumed && !is_interacting) {708 709            const llama_token id = common_sampler_sample(smpl, ctx, -1);710 711            common_sampler_accept(smpl, id, /* accept_grammar= */ true);712 713            // LOG_DBG("last: %s\n", string_from(ctx, smpl->prev.to_vector()).c_str());714 715            embd.push_back(id);716 717            if (params.conversation_mode && !waiting_for_first_input && !llama_vocab_is_eog(vocab, id)) {718                assistant_ss << common_token_to_piece(ctx, id, false);719            }720 721            // echo this to console722            input_echo = true;723 724            // decrement remaining sampling budget725            --n_remain;726 727            LOG_DBG("n_remain: %d\n", n_remain);728        } else {729            // some user input remains from prompt or interaction, forward it to processing730            LOG_DBG("embd_inp.size(): %d, n_consumed: %d\n", (int) embd_inp.size(), n_consumed);731            while ((int) embd_inp.size() > n_consumed) {732                embd.push_back(embd_inp[n_consumed]);733 734                // push the prompt in the sampling context in order to apply repetition penalties later735                // for the prompt, we don't apply grammar rules736                common_sampler_accept(smpl, embd_inp[n_consumed], /* accept_grammar= */ false);737 738                ++n_consumed;739                if ((int) embd.size() == params.n_batch) {740                    break;741                }742            }743        }744 745        // display text746        if (input_echo && display) {747            for (auto id : embd) {748                const std::string token_str = common_token_to_piece(ctx, id, params.special);749 750                // Console/Stream Output751                LOG("%s", token_str.c_str());752 753                // Record Displayed Tokens To Log754                // Note: Generated tokens are created one by one hence this check755                if (embd.size() > 1) {756                    // Incoming Requested Tokens757                    input_tokens.push_back(id);758                } else {759                    // Outgoing Generated Tokens760                    output_tokens.push_back(id);761                    output_ss << token_str;762                }763            }764        }765 766        // reset color to default if there is no pending user input767        if (input_echo && (int) embd_inp.size() == n_consumed) {768            console::set_display(DISPLAY_TYPE_RESET);769            display = true;770        }771 772        // if not currently processing queued inputs;773        if ((int) embd_inp.size() <= n_consumed) {774            // check for reverse prompt in the last n_prev tokens775            if (!params.antiprompt.empty()) {776                const int n_prev = 32;777                const std::string last_output = common_sampler_prev_str(smpl, ctx, n_prev);778 779                is_antiprompt = false;780                // Check if each of the reverse prompts appears at the end of the output.781                // If we're not running interactively, the reverse prompt might be tokenized with some following characters782                // so we'll compensate for that by widening the search window a bit.783                for (std::string & antiprompt : params.antiprompt) {784                    size_t extra_padding = params.interactive ? 0 : 2;785                    size_t search_start_pos = last_output.length() > static_cast<size_t>(antiprompt.length() + extra_padding)786                        ? last_output.length() - static_cast<size_t>(antiprompt.length() + extra_padding)787                        : 0;788 789                    if (last_output.find(antiprompt, search_start_pos) != std::string::npos) {790                        if (params.interactive) {791                            is_interacting = true;792                        }793                        is_antiprompt = true;794                        break;795                    }796                }797 798                // check for reverse prompt using special tokens799                // avoid calling common_sampler_last() if last_output is empty800                if (!last_output.empty()) {801                    llama_token last_token = common_sampler_last(smpl);802                    for (auto token : antiprompt_token) {803                        if (token == last_token) {804                            if (params.interactive) {805                                is_interacting = true;806                            }807                            is_antiprompt = true;808                            break;809                        }810                    }811                }812 813                if (is_antiprompt) {814                    LOG_DBG("found antiprompt: %s\n", last_output.c_str());815                }816            }817 818            // deal with end of generation tokens in interactive mode819            if (!waiting_for_first_input && llama_vocab_is_eog(vocab, common_sampler_last(smpl))) {820                LOG_DBG("found an EOG token\n");821 822                if (params.interactive) {823                    if (!params.antiprompt.empty()) {824                        // tokenize and inject first reverse prompt825                        const auto first_antiprompt = common_tokenize(ctx, params.antiprompt.front(), false, true);826                        embd_inp.insert(embd_inp.end(), first_antiprompt.begin(), first_antiprompt.end());827                        is_antiprompt = true;828                    }829 830                    if (params.enable_chat_template) {831                        chat_add_and_format("assistant", assistant_ss.str());832                    }833                    is_interacting = true;834                    LOG("\n");835                }836            }837 838            if (params.conversation_mode && !waiting_for_first_input) {839                if (!prompt.empty()) {840                    prompt.clear();841                    is_interacting = false;842                }843            }844 845            if ((n_past > 0 || waiting_for_first_input) && is_interacting) {846                LOG_DBG("waiting for user input\n");847 848                if (params.conversation_mode) {849                    LOG("\n> ");850                }851 852                if (params.input_prefix_bos) {853                    LOG_DBG("adding input prefix BOS token\n");854                    embd_inp.push_back(llama_vocab_bos(vocab));855                }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 863                // color user input only864                console::set_display(DISPLAY_TYPE_USER_INPUT);865                display = params.display_prompt;866 867                std::string line;868                bool another_line = true;869                do {870                    another_line = console::readline(line, params.multiline_input);871                    buffer += line;872                } while (another_line);873 874                // done taking input, reset color875                console::set_display(DISPLAY_TYPE_RESET);876                display = true;877 878                if (buffer.empty()) { // Ctrl+D on empty line exits879                    LOG("EOF by user\n");880                    break;881                }882 883                if (buffer.back() == '\n') {884                    // Implement #587:885                    // If the user wants the text to end in a newline,886                    // this should be accomplished by explicitly adding a newline by using \ followed by return,887                    // then returning control by pressing return again.888                    buffer.pop_back();889                }890 891                if (buffer.empty()) { // Enter key on empty line lets the user pass control back892                    LOG_DBG("empty line, passing control back\n");893                } else { // Add tokens to embd only if the input buffer is non-empty894                    // append input suffix if any895                    if (!params.input_suffix.empty() && !params.conversation_mode) {896                        LOG_DBG("appending input suffix: '%s'\n", params.input_suffix.c_str());897                        LOG("%s", params.input_suffix.c_str());898                    }899 900                    LOG_DBG("buffer: '%s'\n", buffer.c_str());901 902                    const size_t original_size = embd_inp.size();903 904                    if (params.escape) {905                        string_process_escapes(buffer);906                    }907 908                    bool format_chat = params.conversation_mode && params.enable_chat_template;909                    std::string user_inp = format_chat910                        ? chat_add_and_format("user", std::move(buffer))911                        : std::move(buffer);912                    // TODO: one inconvenient of current chat template implementation is that we can't distinguish between user input and special tokens (prefix/postfix)913                    const auto line_pfx = common_tokenize(ctx, params.input_prefix, false, true);914                    const auto line_inp = common_tokenize(ctx, user_inp,            false, format_chat);915                    const auto line_sfx = common_tokenize(ctx, params.input_suffix, false, true);916 917                    LOG_DBG("input tokens: %s\n", string_from(ctx, line_inp).c_str());918 919                    // if user stop generation mid-way, we must add EOT to finish model's last response920                    if (need_insert_eot && format_chat) {921                        llama_token eot = llama_vocab_eot(vocab);922                        embd_inp.push_back(eot == LLAMA_TOKEN_NULL ? llama_vocab_eos(vocab) : eot);923                        need_insert_eot = false;924                    }925 926                    embd_inp.insert(embd_inp.end(), line_pfx.begin(), line_pfx.end());927                    embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());928                    embd_inp.insert(embd_inp.end(), line_sfx.begin(), line_sfx.end());929 930                    if (params.verbose_prompt) {931                        LOG_INF("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size() - original_size);932                    }933 934                    for (size_t i = original_size; i < embd_inp.size(); ++i) {935                        const llama_token token = embd_inp[i];936                        const std::string token_str = common_token_to_piece(ctx, token);937                        output_tokens.push_back(token);938                        output_ss << token_str;939 940                        if (params.verbose_prompt) {941                            LOG_INF("%6d -> '%s'\n", token, token_str.c_str());942                        }943                    }944 945                    // reset assistant message946                    assistant_ss.str("");947 948                    n_remain -= line_inp.size();949                    LOG_DBG("n_remain: %d\n", n_remain);950                }951 952                input_echo = false; // do not echo this again953            }954 955            if (n_past > 0 || waiting_for_first_input) {956                if (is_interacting) {957                    common_sampler_reset(smpl);958                }959                is_interacting = false;960 961                if (waiting_for_first_input && params.single_turn) {962                    params.interactive = false;963                    params.interactive_first = false;964                }965                waiting_for_first_input = false;966            }967        }968 969        // end of generation970        if (!embd.empty() && llama_vocab_is_eog(vocab, embd.back()) && !(params.interactive)) {971            LOG(" [end of text]\n");972            break;973        }974 975        // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.976        // We skip this logic when n_predict == -1 (infinite) or -2 (stop at context size).977        if (params.interactive && n_remain <= 0 && params.n_predict >= 0) {978            n_remain = params.n_predict;979            is_interacting = true;980        }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        session_tokens.insert(session_tokens.end(), embd.begin(), embd.end());986        llama_state_save_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());987        LOG_INF("saved final session to %s, n_tokens = %zu\n", path_session.data(), session_tokens.size());988 989    }990 991    LOG("\n\n");992    common_perf_print(ctx, smpl);993 994    llama_backend_free();995 996    ggml_threadpool_free_fn(threadpool);997    ggml_threadpool_free_fn(threadpool_batch);998 999    return 0;1000}1001 
Brunobkr/llama.cpp_AlgMor24_github · Team Ai