mirror of
https://github.com/ikawrakow/ik_llama.cpp.git
synced 2026-01-26 17:20:01 +00:00
* model : Granite docling + Idefics3 preprocessing (SmolVLM) (#16206) * feat: Add granite-docling conversion using trillion pretokenizer Branch: gabe-l-hart/GraniteDocling Signed-off-by: Gabe Goodhart <ghart@us.ibm.com> * feat: Add granite-docling vocab pre enum Branch: gabe-l-hart/GraniteDocling Signed-off-by: Gabe Goodhart <ghart@us.ibm.com> * fix: Use granite-docling pre Branch: gabe-l-hart/GraniteDocling Signed-off-by: Gabe Goodhart <ghart@us.ibm.com> * feat: Add clip_is_idefics3 Branch: gabe-l-hart/GraniteDocling Signed-off-by: Gabe Goodhart <ghart@us.ibm.com> * feat: Allow multi-token boundary sequences for image templating Branch: gabe-l-hart/GraniteDocling Signed-off-by: Gabe Goodhart <ghart@us.ibm.com> * feat: Add tiling support for idefices3 in clip.cpp This should likely be moved into llava_uhd::get_slice_instructions, but for now this avoids disrupting the logic there. Branch: gabe-l-hart/GraniteDocling Signed-off-by: Gabe Goodhart <ghart@us.ibm.com> * feat: Partial support for full templating for idefics3 in mtmd There are still errors encoding some of the image chunks, but the token sequence now matches transformers _almost_ perfectly, except for the double newline before the global image which shows up as two consecutive newline tokens instead of a single double-newline token. I think this is happening because the blocks are tokenized separately then concatenated. Branch: gabe-l-hart/GraniteDocling Signed-off-by: Gabe Goodhart <ghart@us.ibm.com> * feat: Fully working image preprocessing for idefics3 w/ resize and slicing Branch: gabe-l-hart/GraniteDocling Signed-off-by: Gabe Goodhart <ghart@us.ibm.com> * feat: Parse the preprocessor config's longest side and add it to the mmproj hparams Branch: GraniteDocling Signed-off-by: Gabe Goodhart <ghart@us.ibm.com> * fix: Use the longest side instead of size * scale_factor For Granite Docling, these come out to the same value, but that was just a conicidence. Branch: GraniteDocling Signed-off-by: Gabe Goodhart <ghart@us.ibm.com> * fix: Allow batch encoding and remove clip_is_idefics3 Branch: GraniteDocling Signed-off-by: Gabe Goodhart <ghart@us.ibm.com> * refactor: Remove unnecessary conditionals for empty token vectors Branch: GraniteDocling Signed-off-by: Gabe Goodhart <ghart@us.ibm.com> * refactor: Use image_manipulation util Branch: GraniteDocling Signed-off-by: Gabe Goodhart <ghart@us.ibm.com> * add test model --------- Signed-off-by: Gabe Goodhart <ghart@us.ibm.com> Co-authored-by: Xuan Son Nguyen <son@huggingface.co> # Conflicts: # convert_hf_to_gguf.py # convert_hf_to_gguf_update.py # gguf-py/gguf/constants.py # gguf-py/gguf/gguf_writer.py # src/llama-vocab.cpp # src/llama-vocab.h * mtmd : support home-cooked Mistral Small Omni (#14928) * model : add LightOnOCR-1B model (#16764) * model : add LightOnOCR-1B model * add test # Conflicts: # convert_hf_to_gguf.py # gguf-py/gguf/constants.py * mtmd : fix idefics3 preprocessing (#16806) * mtmd : fix idefics3 preprocessing * disable granite test * fix test for granite * model: Add support for CogVLM model (#15002) * Added GGUF mappings for CogVLM model * Add tensor mapping for CogVLM visual encoder * Add CogVLM to conversion script, no vision part yet * Added CogVLM vision model to conversion script * Add graph for CogVLM CLIP model * Add graph for CogVLM * Fixes for CogVLM. Now compiles. * Model now runs * Fixes for cogvlm graph * Account for graph context change after rebase * Changes for whitespace * Changes in convert script according to comments * Switch CogVLM LLM graph to merged QKV tensor * Use rope_type variable instead of direct definition * Change CogVLM CLIP encoder to use SWIGLU * Switch CogVLM CLIP to use merged QKV * Apply rebase edits and remove ggml_cont call that is now unnecessary * clean up --------- Co-authored-by: Xuan Son Nguyen <son@huggingface.co> # Conflicts: # convert_hf_to_gguf.py # examples/mtmd/clip.cpp # gguf-py/gguf/constants.py # gguf-py/gguf/tensor_mapping.py # src/llama-arch.cpp # src/llama-arch.h # src/llama-model.cpp # src/llama-model.h * mtmd: refactor preprocessing + support max/min pixels (#16878) * mtmd: refactor preprocessing + support max/min pixels * fix mlp type * implement mix/max pixels * improve hparams * better image preproc for qwen * fix * fix out of bound composite * fix (2) * fix token calculation * get_merge_kernel_size() * fix llama4 and lfm2 * gonna fix them all * use simple resize for qwen * qwen: increase min tokens * no resize if dst size == src size * restore to initial min/max tokens value for qwen # Conflicts: # examples/mtmd/clip.cpp * clip : use FA (#16837) * clip : use FA * cont : add warning about unsupported ops * implement "auto" mode for clip flash attn * clip : print more detailed op support info during warmup * cont : remove obsolete comment [no ci] * improve debugging message * trailing space * metal : remove stray return --------- Co-authored-by: Xuan Son Nguyen <son@huggingface.co> * model: add Janus Pro for image understanding (#16906) * Add support for Janus Pro * Update gguf-py/gguf/tensor_mapping.py Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> * Update gguf-py/gguf/tensor_mapping.py Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> * Address reviewer suggestions Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> * Add JANUS_PRO constant * Update clip model handling Co-authored-by: Xuan-Son Nguyen <son@huggingface.co> * Update tools/mtmd/clip.cpp Co-authored-by: Xuan-Son Nguyen <thichthat@gmail.com> * Refactor JANUS_PRO handling in clip.cpp Co-authored-by: Xuan-Son Nguyen <son@huggingface.co> * Update tools/mtmd/clip.cpp Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> * em whitespace --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> Co-authored-by: Xuan-Son Nguyen <son@huggingface.co> Co-authored-by: Xuan-Son Nguyen <thichthat@gmail.com> # Conflicts: # convert_hf_to_gguf.py # gguf-py/gguf/constants.py # gguf-py/gguf/tensor_mapping.py * mtmd: pad mask for qwen2.5vl (#16954) * mtmd: pad mask for qwen2.5vl * improve * mtmd: add --image-min/max-tokens (#16921) * mtmd: improve struct initialization (#16981) * mtmd: allow QwenVL to process larger image by default (#17020) * Disable flash attention * mtmd : fix embedding size for image input (#17123) * mtmd: fix patch_size initialized to random value in audio models (#17128) * mtmd: fix patch_size initialized to random value in audio models * add default hparams * add llama_model_n_embd_inp * Fix load qwen3 vl Change batch size * Add description * Fix cli build error --------- Signed-off-by: Gabe Goodhart <ghart@us.ibm.com> Co-authored-by: Gabe Goodhart <ghart@us.ibm.com> Co-authored-by: Xuan Son Nguyen <son@huggingface.co> Co-authored-by: Tianyue-Zhao <zhaotianyue@outlook.com> Co-authored-by: Georgi Gerganov <ggerganov@gmail.com> Co-authored-by: Zhiyong Wang <85110830+ravenouse@users.noreply.github.com> Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> Co-authored-by: Xuan-Son Nguyen <thichthat@gmail.com> Co-authored-by: firecoperana <firecoperana>
449 lines
15 KiB
C++
449 lines
15 KiB
C++
//#include "arg.h"
|
|
#include "log.h"
|
|
#include "common.h"
|
|
#include "sampling.h"
|
|
#include "llama.h"
|
|
#include "ggml.h"
|
|
#include "console.h"
|
|
#include "chat.h"
|
|
#include "mtmd.h"
|
|
#include "mtmd-helper.h"
|
|
|
|
#include <vector>
|
|
#include <limits.h>
|
|
#include <cinttypes>
|
|
|
|
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
|
|
#include <signal.h>
|
|
#include <unistd.h>
|
|
#elif defined (_WIN32)
|
|
#define WIN32_LEAN_AND_MEAN
|
|
#ifndef NOMINMAX
|
|
#define NOMINMAX
|
|
#endif
|
|
#include <windows.h>
|
|
#include <signal.h>
|
|
#endif
|
|
|
|
// volatile, because of signal being an interrupt
|
|
static volatile bool g_is_generating = false;
|
|
static volatile bool g_is_interrupted = false;
|
|
|
|
/**
|
|
* Please note that this is NOT a production-ready stuff.
|
|
* It is a playground for trying multimodal support in llama.cpp.
|
|
* For contributors: please keep this code simple and easy to understand.
|
|
*/
|
|
|
|
static void show_additional_info(int /*argc*/, char ** argv) {
|
|
LOG_TEE(
|
|
"Experimental CLI for multimodal\n\n"
|
|
"Usage: %s [options] -m <model> --mmproj <mmproj> --image <image> --audio <audio> -p <prompt>\n\n"
|
|
" -m and --mmproj are required\n"
|
|
" -hf user/repo can replace both -m and --mmproj in most cases\n"
|
|
" --image, --audio and -p are optional, if NOT provided, the CLI will run in chat mode\n"
|
|
" to disable using GPU for mmproj model, add --no-mmproj-offload\n",
|
|
argv[0]
|
|
);
|
|
}
|
|
|
|
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
|
|
static void sigint_handler(int signo) {
|
|
if (signo == SIGINT) {
|
|
if (g_is_generating) {
|
|
g_is_generating = false;
|
|
} else {
|
|
console::cleanup();
|
|
if (g_is_interrupted) {
|
|
_exit(1);
|
|
}
|
|
g_is_interrupted = true;
|
|
}
|
|
}
|
|
}
|
|
#endif
|
|
|
|
// ======================= compat ================================
|
|
using common_init_result = llama_init_result;
|
|
using common_sampler = llama_sampling_context;
|
|
using llama_tokens = std::vector<llama_token>;
|
|
using common_params = gpt_params;
|
|
|
|
inline common_init_result common_init_from_params(gpt_params & params) {
|
|
return llama_init_from_gpt_params(params);
|
|
}
|
|
inline llama_sampling_context * common_sampler_init(const llama_model * model, const llama_sampling_params & sparams) {
|
|
return llama_sampling_init(llama_get_model_vocab(model), sparams);
|
|
}
|
|
inline std::vector<llama_token> common_tokenize(const llama_context * ctx, const std::string & text, bool add_special, bool parse_special = false) {
|
|
return llama_tokenize(ctx, text, add_special, parse_special);
|
|
}
|
|
inline void common_sampler_free(common_sampler * smpl) {
|
|
llama_sampling_free(smpl);
|
|
}
|
|
inline llama_token common_sampler_sample(common_sampler * gsmpl, llama_context * ctx, int idx, [[maybe_unused]] bool grammar_first = false) {
|
|
return llama_sampling_sample(gsmpl, ctx, nullptr, idx);
|
|
}
|
|
inline void common_sampler_accept(common_sampler * gsmpl, llama_context * ctx, llama_token token, bool accept_grammar) {
|
|
llama_sampling_accept(gsmpl, ctx, token, accept_grammar);
|
|
}
|
|
inline std::string common_token_to_piece(const llama_context * ctx, llama_token token, bool special = true) {
|
|
return llama_token_to_piece(ctx, token, special);
|
|
}
|
|
inline void common_batch_clear(llama_batch & batch) {
|
|
llama_batch_clear(batch);
|
|
}
|
|
inline void common_batch_add(llama_batch & batch, llama_token id, llama_pos pos, const std::vector<llama_seq_id> & seq_ids, bool logits) {
|
|
llama_batch_add(batch, id, pos, seq_ids, logits);
|
|
}
|
|
void common_init() {
|
|
#ifdef NDEBUG
|
|
const char * build_type = "";
|
|
#else
|
|
const char * build_type = " (debug)";
|
|
#endif
|
|
LOG_TEE("build: %d (%s) with %s for %s%s\n", LLAMA_BUILD_NUMBER, LLAMA_COMMIT, LLAMA_COMPILER, LLAMA_BUILD_TARGET, build_type);
|
|
}
|
|
|
|
|
|
#ifndef LOG_ERR
|
|
#define LOG_ERR LOG_TEE
|
|
#endif
|
|
#ifndef LOG_INF
|
|
#define LOG_INF LOG_TEE
|
|
#endif
|
|
#ifndef LOG_DBG
|
|
#define LOG_DBG LOG
|
|
#endif
|
|
// ======================= end compat ================================
|
|
|
|
struct mtmd_cli_context {
|
|
mtmd::context_ptr ctx_vision;
|
|
common_init_result llama_init;
|
|
|
|
llama_model * model;
|
|
llama_context * lctx;
|
|
const llama_vocab * vocab;
|
|
common_sampler * smpl;
|
|
llama_batch batch;
|
|
int n_batch;
|
|
|
|
mtmd::bitmaps bitmaps;
|
|
|
|
// note: we know that gemma3 template is "linear", meaning each turn is completely separated to another
|
|
// so here we don't need to keep track of chat history
|
|
common_chat_templates_ptr tmpls;
|
|
|
|
// support for legacy templates (models not having EOT token)
|
|
llama_tokens antiprompt_tokens;
|
|
|
|
int n_threads = 1;
|
|
llama_pos n_past = 0;
|
|
|
|
mtmd_cli_context(common_params & params) : llama_init(common_init_from_params(params)) {
|
|
model = llama_init.model; //.get();
|
|
lctx = llama_init.context; //.get();
|
|
vocab = llama_model_get_vocab(model);
|
|
smpl = common_sampler_init(model, params.sparams); //sampling);
|
|
n_threads = params.n_threads;
|
|
batch = llama_batch_init(1, 0, 1); // batch for next token generation
|
|
n_batch = params.n_batch;
|
|
|
|
if (!model || !lctx) {
|
|
exit(1);
|
|
}
|
|
|
|
if (!llama_model_chat_template(model, nullptr) && params.chat_template.empty()) {
|
|
LOG_ERR("Model does not have chat template.\n");
|
|
LOG_ERR(" For old llava models, you may need to use '--chat-template vicuna'\n");
|
|
LOG_ERR(" For MobileVLM models, use '--chat-template deepseek'\n");
|
|
LOG_ERR(" For Mistral Small 3.1, use '--chat-template mistral-v7'\n");
|
|
exit(1);
|
|
}
|
|
|
|
tmpls = common_chat_templates_init(model, params.chat_template);
|
|
LOG_TEE("%s: chat template example:\n%s\n", __func__, common_chat_format_example(tmpls.get(), params.use_jinja, params.default_template_kwargs).c_str());
|
|
|
|
init_vision_context(params);
|
|
|
|
// load antiprompt tokens for legacy templates
|
|
if (params.chat_template == "vicuna") {
|
|
antiprompt_tokens = common_tokenize(lctx, "ASSISTANT:", false, true);
|
|
} else if (params.chat_template == "deepseek") {
|
|
antiprompt_tokens = common_tokenize(lctx, "###", false, true);
|
|
}
|
|
}
|
|
|
|
~mtmd_cli_context() {
|
|
llama_batch_free(batch);
|
|
common_sampler_free(smpl);
|
|
}
|
|
|
|
void init_vision_context(common_params & params) {
|
|
const char * clip_path = params.mmproj.path.c_str();
|
|
mtmd_context_params mparams = mtmd_context_params_default();
|
|
mparams.use_gpu = params.mmproj_use_gpu;
|
|
mparams.print_timings = true;
|
|
mparams.n_threads = params.n_threads;
|
|
mparams.verbosity = params.verbosity > 0 ? GGML_LOG_LEVEL_DEBUG : GGML_LOG_LEVEL_INFO;
|
|
mparams.flash_attn_type = params.flash_attn ? LLAMA_FLASH_ATTN_TYPE_ENABLED : LLAMA_FLASH_ATTN_TYPE_DISABLED;
|
|
mparams.image_min_tokens = params.image_min_tokens;
|
|
mparams.image_max_tokens = params.image_max_tokens;
|
|
ctx_vision.reset(mtmd_init_from_file(clip_path, model, mparams));
|
|
if (!ctx_vision.get()) {
|
|
LOG_ERR("Failed to load vision model from %s\n", clip_path);
|
|
exit(1);
|
|
}
|
|
}
|
|
|
|
bool check_antiprompt(const llama_tokens & generated_tokens) {
|
|
if (antiprompt_tokens.empty() || generated_tokens.size() < antiprompt_tokens.size()) {
|
|
return false;
|
|
}
|
|
return std::equal(
|
|
generated_tokens.end() - antiprompt_tokens.size(),
|
|
generated_tokens.end(),
|
|
antiprompt_tokens.begin()
|
|
);
|
|
}
|
|
|
|
bool load_media(const std::string & fname) {
|
|
mtmd::bitmap bmp(mtmd_helper_bitmap_init_from_file(ctx_vision.get(), fname.c_str()));
|
|
if (!bmp.ptr) {
|
|
return false;
|
|
}
|
|
bitmaps.entries.push_back(std::move(bmp));
|
|
return true;
|
|
}
|
|
};
|
|
|
|
static int generate_response(mtmd_cli_context & ctx, int n_predict) {
|
|
llama_tokens generated_tokens;
|
|
for (int i = 0; i < n_predict; i++) {
|
|
if (i > n_predict || !g_is_generating || g_is_interrupted) {
|
|
LOG_TEE("\n");
|
|
break;
|
|
}
|
|
|
|
llama_token token_id = common_sampler_sample(ctx.smpl, ctx.lctx, -1);
|
|
generated_tokens.push_back(token_id);
|
|
common_sampler_accept(ctx.smpl, ctx.lctx, token_id, true);
|
|
|
|
if (llama_vocab_is_eog(ctx.vocab, token_id) || ctx.check_antiprompt(generated_tokens)) {
|
|
LOG_TEE("\n");
|
|
break; // end of generation
|
|
}
|
|
|
|
LOG_TEE("%s", common_token_to_piece(ctx.lctx, token_id).c_str());
|
|
fflush(stdout);
|
|
|
|
if (g_is_interrupted) {
|
|
LOG_TEE("\n");
|
|
break;
|
|
}
|
|
|
|
// eval the token
|
|
common_batch_clear(ctx.batch);
|
|
common_batch_add(ctx.batch, token_id, ctx.n_past++, {0}, true);
|
|
if (llama_decode(ctx.lctx, ctx.batch)) {
|
|
LOG_ERR("failed to decode token\n");
|
|
return 1;
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
static int eval_message(mtmd_cli_context & ctx, common_chat_msg & msg, bool add_bos = false) {
|
|
common_chat_templates_inputs tmpl_inputs;
|
|
tmpl_inputs.messages = {msg};
|
|
tmpl_inputs.add_generation_prompt = true;
|
|
tmpl_inputs.use_jinja = false; // jinja is buggy here
|
|
auto formatted_chat = common_chat_templates_apply(ctx.tmpls.get(), tmpl_inputs);
|
|
LOG_DBG("formatted_chat.prompt: %s\n", formatted_chat.prompt.c_str());
|
|
|
|
mtmd_input_text text;
|
|
text.text = formatted_chat.prompt.c_str();
|
|
text.add_special = add_bos;
|
|
text.parse_special = true;
|
|
|
|
if (g_is_interrupted) return 0;
|
|
|
|
mtmd::input_chunks chunks(mtmd_input_chunks_init());
|
|
auto bitmaps_c_ptr = ctx.bitmaps.c_ptr();
|
|
int32_t res = mtmd_tokenize(ctx.ctx_vision.get(),
|
|
chunks.ptr.get(), // output
|
|
&text, // text
|
|
bitmaps_c_ptr.data(),
|
|
bitmaps_c_ptr.size());
|
|
if (res != 0) {
|
|
LOG_ERR("Unable to tokenize prompt, res = %d\n", res);
|
|
return 1;
|
|
}
|
|
|
|
ctx.bitmaps.entries.clear();
|
|
|
|
llama_pos new_n_past;
|
|
if (mtmd_helper_eval_chunks(ctx.ctx_vision.get(),
|
|
ctx.lctx, // lctx
|
|
chunks.ptr.get(), // chunks
|
|
ctx.n_past, // n_past
|
|
0, // seq_id
|
|
ctx.n_batch, // n_batch
|
|
true, // logits_last
|
|
&new_n_past)) {
|
|
LOG_ERR("Unable to eval prompt\n");
|
|
return 1;
|
|
}
|
|
|
|
ctx.n_past = new_n_past;
|
|
|
|
LOG("\n");
|
|
|
|
return 0;
|
|
}
|
|
|
|
int main(int argc, char ** argv) {
|
|
ggml_time_init();
|
|
|
|
common_params params;
|
|
params.sparams.temp = 0.2; // lower temp by default for better quality
|
|
|
|
if (!gpt_params_parse(argc, argv, params)) {
|
|
return 1;
|
|
}
|
|
//if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_MTMD, show_additional_info)) {
|
|
// return 1;
|
|
//}
|
|
|
|
common_init();
|
|
|
|
if (params.mmproj.path.empty()) {
|
|
show_additional_info(argc, argv);
|
|
LOG_ERR("ERR: Missing --mmproj argument\n");
|
|
return 1;
|
|
}
|
|
|
|
mtmd_cli_context ctx(params);
|
|
LOG("%s: loading model: %s\n", __func__, params.model.c_str());
|
|
|
|
bool is_single_turn = !params.prompt.empty() && !params.image.empty();
|
|
|
|
int n_predict = params.n_predict < 0 ? INT_MAX : params.n_predict;
|
|
|
|
// Ctrl+C handling
|
|
{
|
|
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
|
|
struct sigaction sigint_action;
|
|
sigint_action.sa_handler = sigint_handler;
|
|
sigemptyset (&sigint_action.sa_mask);
|
|
sigint_action.sa_flags = 0;
|
|
sigaction(SIGINT, &sigint_action, NULL);
|
|
#elif defined (_WIN32)
|
|
auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
|
|
return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
|
|
};
|
|
SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
|
|
#endif
|
|
}
|
|
|
|
if (g_is_interrupted) return 130;
|
|
|
|
if (is_single_turn) {
|
|
g_is_generating = true;
|
|
if (params.prompt.find(mtmd_default_marker()) == std::string::npos) {
|
|
for (size_t i = 0; i < params.image.size(); i++) {
|
|
params.prompt += mtmd_default_marker();
|
|
}
|
|
}
|
|
common_chat_msg msg;
|
|
msg.role = "user";
|
|
msg.content = params.prompt;
|
|
for (const auto & image : params.image) {
|
|
if (!ctx.load_media(image)) {
|
|
return 1; // error is already printed by libmtmd
|
|
}
|
|
}
|
|
if (eval_message(ctx, msg, true)) {
|
|
return 1;
|
|
}
|
|
if (!g_is_interrupted && generate_response(ctx, n_predict)) {
|
|
return 1;
|
|
}
|
|
|
|
} else {
|
|
LOG_TEE("\n Running in chat mode, available commands:");
|
|
if (mtmd_support_vision(ctx.ctx_vision.get())) {
|
|
LOG_TEE("\n /image <path> load an image");
|
|
}
|
|
if (mtmd_support_audio(ctx.ctx_vision.get())) {
|
|
LOG_TEE("\n /audio <path> load an audio");
|
|
}
|
|
LOG_TEE("\n /clear clear the chat history");
|
|
LOG_TEE("\n /quit or /exit exit the program");
|
|
LOG_TEE("\n");
|
|
|
|
bool is_first_msg = true;
|
|
std::string content;
|
|
|
|
while (!g_is_interrupted) {
|
|
g_is_generating = false;
|
|
LOG_TEE("\n> ");
|
|
console::set_display(console::user_input);
|
|
std::string line;
|
|
console::readline(line, false);
|
|
if (g_is_interrupted) break;
|
|
console::set_display(console::reset);
|
|
line = string_strip(line);
|
|
if (line.empty()) {
|
|
continue;
|
|
}
|
|
if (line == "/quit" || line == "/exit") {
|
|
break;
|
|
}
|
|
if (line == "/clear") {
|
|
ctx.n_past = 0;
|
|
llama_kv_cache_seq_rm(ctx.lctx, 0, 1, -1);
|
|
//llama_memory_seq_rm(llama_get_memory(ctx.lctx), 0, 1, -1); // keep BOS
|
|
LOG_TEE("Chat history cleared\n\n");
|
|
continue;
|
|
}
|
|
g_is_generating = true;
|
|
bool is_image = line == "/image" || line.find("/image ") == 0;
|
|
bool is_audio = line == "/audio" || line.find("/audio ") == 0;
|
|
if (is_image || is_audio) {
|
|
if (line.size() < 8) {
|
|
LOG_ERR("ERR: Missing media filename\n");
|
|
continue;
|
|
}
|
|
std::string media_path = line.substr(7);
|
|
if (ctx.load_media(media_path)) {
|
|
LOG_TEE("%s %s loaded\n", media_path.c_str(), is_image ? "image" : "audio");
|
|
content += mtmd_default_marker();
|
|
}
|
|
// else, error is already printed by libmtmd
|
|
continue;
|
|
} else {
|
|
content += line;
|
|
}
|
|
common_chat_msg msg;
|
|
msg.role = "user";
|
|
msg.content = content;
|
|
int ret = eval_message(ctx, msg, is_first_msg);
|
|
if (ret) {
|
|
return 1;
|
|
}
|
|
if (g_is_interrupted) break;
|
|
if (generate_response(ctx, n_predict)) {
|
|
return 1;
|
|
}
|
|
content.clear();
|
|
is_first_msg = false;
|
|
}
|
|
}
|
|
if (g_is_interrupted) LOG_TEE("\nInterrupted by user\n");
|
|
LOG_TEE("\n\n");
|
|
llama_print_timings(ctx.lctx);
|
|
//llama_perf_context_print(ctx.lctx);
|
|
return g_is_interrupted ? 130 : 0;
|
|
}
|