From f3b9369f988e210d278ef9d1bac65e64648d628f Mon Sep 17 00:00:00 2001 From: cailinxi Date: Sat, 28 Feb 2026 03:54:40 +0000 Subject: [PATCH 01/40] feat(mtmd): add EP vision variant of llama-mtmd-cli Add llama-mtmd-cli-ep, a multimodal CLI that replaces mtmd's CLIP/GGUF vision encoding with Spacemit EP's ONNX vision engine. This bypasses the mtmd chunk mechanism (which requires mmproj GGUF) and instead performs embedding-level fusion: text tokens are mapped to embeddings via an external embedding table, concatenated withONNX-encoded image embeddings, and decoded as a single embd batch. New files: - ep-vision-wrapper.h/cpp: pimpl wrapper for SpineVisionModelEngine - mtmd-cli-ep.cpp: multimodal CLI with EP vision support - CMakeLists.txt: MTMD_BUILD_EP_CLI conditional build target Change-Id: Idec5fea42a2a166ebf44463b60258e1dedb36e7e --- tools/mtmd/CMakeLists.txt | 54 +++ tools/mtmd/ep-vision-wrapper.cpp | 70 ++++ tools/mtmd/ep-vision-wrapper.h | 39 ++ tools/mtmd/mtmd-cli-ep.cpp | 679 +++++++++++++++++++++++++++++++ 4 files changed, 842 insertions(+) create mode 100644 tools/mtmd/ep-vision-wrapper.cpp create mode 100644 tools/mtmd/ep-vision-wrapper.h create mode 100644 tools/mtmd/mtmd-cli-ep.cpp diff --git a/tools/mtmd/CMakeLists.txt b/tools/mtmd/CMakeLists.txt index a76adc9b80bd..97be4b416ec1 100644 --- a/tools/mtmd/CMakeLists.txt +++ b/tools/mtmd/CMakeLists.txt @@ -122,3 +122,57 @@ add_executable(llama-mtmd-debug debug/mtmd-debug.cpp) set_target_properties(llama-mtmd-debug PROPERTIES OUTPUT_NAME llama-mtmd-debug) target_link_libraries(llama-mtmd-debug PRIVATE llama-common mtmd Threads::Threads) target_compile_features(llama-mtmd-debug PRIVATE cxx_std_17) + +# ============================================================ +# EP Vision variant of mtmd-cli +# Uses Spacemit EP ONNX vision engine instead of CLIP/GGUF +# ============================================================ +option(MTMD_BUILD_EP_CLI "Build mtmd-cli with Spacemit EP vision support" OFF) + +if(MTMD_BUILD_EP_CLI) + if(NOT DEFINED SPACEMIT_EP_DIR) + message(FATAL_ERROR "SPACEMIT_EP_DIR must be set when MTMD_BUILD_EP_CLI=ON") + endif() + if(NOT DEFINED ONNXRUNTIME_INC_DIR) + message(FATAL_ERROR "ONNXRUNTIME_INC_DIR must be set when MTMD_BUILD_EP_CLI=ON") + endif() + if(NOT DEFINED ONNXRUNTIME_LIB_DIR) + message(FATAL_ERROR "ONNXRUNTIME_LIB_DIR must be set when MTMD_BUILD_EP_CLI=ON") + endif() + + set(EP_TARGET llama-mtmd-cli-ep) + add_executable(${EP_TARGET} + mtmd-cli-ep.cpp + ep-vision-wrapper.cpp + ${SPACEMIT_EP_DIR}/src/llm/spine_vision_engine.cc + ${SPACEMIT_EP_DIR}/src/llm/spine_llm_argparser.cc + ) + set_target_properties(${EP_TARGET} PROPERTIES OUTPUT_NAME llama-mtmd-cli-ep) + + target_include_directories(${EP_TARGET} PRIVATE + . + ../.. + ../../vendor + ${SPACEMIT_EP_DIR}/src/llm + ${ONNXRUNTIME_INC_DIR} + ) + + target_link_directories(${EP_TARGET} PRIVATE + ${ONNXRUNTIME_LIB_DIR} + ) + + target_link_libraries(${EP_TARGET} PRIVATE + llama-common + llama + ggml + onnxruntime + dl + Threads::Threads + ) + + target_compile_features(${EP_TARGET} PRIVATE cxx_std_17) + + if(LLAMA_TOOLS_INSTALL) + install(TARGETS ${EP_TARGET} RUNTIME) + endif() +endif() diff --git a/tools/mtmd/ep-vision-wrapper.cpp b/tools/mtmd/ep-vision-wrapper.cpp new file mode 100644 index 000000000000..3b4d3e17e858 --- /dev/null +++ b/tools/mtmd/ep-vision-wrapper.cpp @@ -0,0 +1,70 @@ +// EP Vision Wrapper - Spacemit EP ONNX vision engine adapter +// Wraps SpineVisionModelEngine and SpineLLMArgParser for use in mtmd-cli-ep + +#include "ep-vision-wrapper.h" + +#include "spine_llm_argparser.h" +#include "spine_vision_engine.h" + +#include +#include +#include + +namespace onnxruntime { +const OrtApi * g_ort = NULL; +} // namespace onnxruntime + +struct ep_vision_context::impl { + onnxruntime::spacemit::SpineModelConfig config; + std::unique_ptr vision_engine; + std::string arch_name; +}; + +ep_vision_context::~ep_vision_context() = default; + +std::unique_ptr ep_vision_context::create(const std::string & config_dir) { + auto ctx = std::unique_ptr(new ep_vision_context()); + ctx->pimpl_ = std::make_unique(); + auto & d = *ctx->pimpl_; + + // 1. Load config from directory + if (!onnxruntime::spacemit::SpineLLMArgParser::LoadConfigFromDir(config_dir, d.config)) { + throw std::runtime_error("Failed to load EP config from: " + config_dir); + } + + if (!d.config.architectures.empty()) { + d.arch_name = d.config.architectures[0]; + } + + // 2. Initialize ORT API + onnxruntime::g_ort = OrtGetApiBase()->GetApi(ORT_API_VERSION); + + // 3. Create vision engine and session + d.vision_engine = std::make_unique(d.config.vision_model_path); + d.vision_engine->CreateVisionModelSession(); + + return ctx; +} + +std::vector ep_vision_context::encode_image(const std::string & binary_path) { + auto & d = *pimpl_; + std::string path_copy = binary_path; + Ort::Value & input_tensor = d.vision_engine->SetInputTensor(path_copy); + return d.vision_engine->RunSession(input_tensor); +} + +int64_t ep_vision_context::hidden_size() const { + return pimpl_->config.hidden_size; +} + +int64_t ep_vision_context::vocab_size() const { + return pimpl_->config.vocab_size; +} + +const std::string & ep_vision_context::token_embedding_path() const { + return pimpl_->config.token_embedding_path; +} + +const std::string & ep_vision_context::architecture() const { + return pimpl_->arch_name; +} diff --git a/tools/mtmd/ep-vision-wrapper.h b/tools/mtmd/ep-vision-wrapper.h new file mode 100644 index 000000000000..07e3201a6696 --- /dev/null +++ b/tools/mtmd/ep-vision-wrapper.h @@ -0,0 +1,39 @@ +// EP Vision Wrapper - Spacemit EP ONNX vision engine adapter for llama-mtmd-cli +// Replaces CLIP/GGUF vision encoding with EP's ONNX vision engine + +#pragma once + +#include +#include +#include +#include + +struct ep_vision_context { + ep_vision_context(const ep_vision_context &) = delete; + ep_vision_context & operator=(const ep_vision_context &) = delete; + ~ep_vision_context(); + + // Initialize from EP config directory (containing config.json) + static std::unique_ptr create(const std::string & config_dir); + + // Encode a preprocessed image binary file using ONNX vision engine + // Returns image embedding vector (n_tokens * hidden_size floats) + std::vector encode_image(const std::string & binary_path); + + // Get the hidden size (embedding dimension) + int64_t hidden_size() const; + + // Get the vocab size + int64_t vocab_size() const; + + // Get the token embedding file path + const std::string & token_embedding_path() const; + + // Get the model architecture name + const std::string & architecture() const; + +private: + ep_vision_context() = default; + struct impl; + std::unique_ptr pimpl_; +}; diff --git a/tools/mtmd/mtmd-cli-ep.cpp b/tools/mtmd/mtmd-cli-ep.cpp new file mode 100644 index 000000000000..83e12883c9b5 --- /dev/null +++ b/tools/mtmd/mtmd-cli-ep.cpp @@ -0,0 +1,679 @@ +// llama-mtmd-cli-ep: Multimodal CLI using Spacemit EP ONNX vision engine +// Based on mtmd-cli.cpp, replaces CLIP/GGUF vision encoding with EP's ONNX vision engine +// LLM inference logic (loading, sampling, generation) is reused from the original mtmd-cli + +#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 "ep-vision-wrapper.h" + +#include +#include +#include +#include +#include +#include + +#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) +#include +#include +#elif defined (_WIN32) +#define WIN32_LEAN_AND_MEAN +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#include +#endif + +static volatile bool g_is_generating = false; +static volatile bool g_is_interrupted = false; + +static void show_additional_info(int /*argc*/, char ** argv) { + LOG( + "Multimodal CLI with Spacemit EP vision engine\n\n" + "Usage: %s [options] -m --ep-config --image -p \n\n" + " -m and --ep-config are required\n" + " --image and -p are optional, if NOT provided, the CLI will run in chat mode\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 + +// ============================================================ +// Token embedding loading and text encoding utilities +// (Adapted from EP's SpineLLMEngine::EncodeUserText) +// ============================================================ + +static bool load_token_embeddings(const std::string & path, + int64_t vocab_size, + int64_t hidden_size, + std::vector & out) { + const size_t total = vocab_size * hidden_size; + out.resize(total); + std::ifstream file(path, std::ios::binary); + if (!file.is_open()) { + LOG_ERR("Failed to open token embedding file: %s\n", path.c_str()); + return false; + } + file.read(reinterpret_cast(out.data()), total * sizeof(float)); + if (!file) { + LOG_ERR("Token embedding file incomplete: %s\n", path.c_str()); + return false; + } + return true; +} + +// Split text at marker, tokenize both parts, look up token embeddings +struct text_encode_result { + std::vector embeddings; + int n_before = 0; + int n_after = 0; +}; + +static text_encode_result encode_user_text( + const llama_vocab * vocab, + const std::string & text, + bool add_bos, + const std::vector & token_embeddings, + int64_t hidden_size) { + text_encode_result result; + + // Split at + std::string before_image, after_image; + size_t image_pos = text.find(""); + if (image_pos != std::string::npos) { + before_image = text.substr(0, image_pos); + size_t after_pos = image_pos + 7; + if (after_pos < text.length() && text[after_pos] == '\n') { + after_pos++; + } + after_image = text.substr(after_pos); + } else { + before_image = text; + } + + // Tokenize before part + std::vector before_tokens(before_image.size() + 64); + int n_before = llama_tokenize(vocab, before_image.c_str(), + static_cast(before_image.length()), + before_tokens.data(), static_cast(before_tokens.size()), + add_bos, true); + if (n_before < 0) { + before_tokens.resize(-n_before); + n_before = llama_tokenize(vocab, before_image.c_str(), + static_cast(before_image.length()), + before_tokens.data(), static_cast(before_tokens.size()), + add_bos, true); + } + before_tokens.resize(n_before); + + // Tokenize after part + std::vector after_tokens; + int n_after = 0; + if (!after_image.empty()) { + after_tokens.resize(after_image.size() + 64); + n_after = llama_tokenize(vocab, after_image.c_str(), + static_cast(after_image.length()), + after_tokens.data(), static_cast(after_tokens.size()), + false, true); + if (n_after < 0) { + after_tokens.resize(-n_after); + n_after = llama_tokenize(vocab, after_image.c_str(), + static_cast(after_image.length()), + after_tokens.data(), static_cast(after_tokens.size()), + false, true); + } + after_tokens.resize(n_after); + } + + result.n_before = n_before; + result.n_after = n_after; + + // Look up token embedding matrix + int total = n_before + n_after; + result.embeddings.resize(total * hidden_size); + + for (int i = 0; i < n_before; ++i) { + const float * src = &token_embeddings[before_tokens[i] * hidden_size]; + float * dst = &result.embeddings[i * hidden_size]; + std::copy_n(src, hidden_size, dst); + } + for (int i = 0; i < n_after; ++i) { + const float * src = &token_embeddings[after_tokens[i] * hidden_size]; + float * dst = &result.embeddings[(n_before + i) * hidden_size]; + std::copy_n(src, hidden_size, dst); + } + + return result; +} + +// ============================================================ +// Multimodal embedding fusion +// [before_text_embd] + [image_embd] + [after_text_embd] +// (Adapted from EP's SpineLLMEngine::MultimodalEmbeddingFusion) +// ============================================================ + +static std::vector fuse_multimodal_embeddings( + const std::vector & image_embd, + const text_encode_result & text_result, + int64_t hidden_size) { + size_t n_image = image_embd.size() / hidden_size; + size_t n_before = text_result.n_before; + size_t n_after = text_result.n_after; + size_t total = n_before + n_image + n_after; + + std::vector fused(total * hidden_size); + size_t offset = 0; + + // [before_text_embd] + std::copy_n(text_result.embeddings.data(), + n_before * hidden_size, + fused.data() + offset); + offset += n_before * hidden_size; + + // [image_embd] + std::copy(image_embd.begin(), image_embd.end(), + fused.data() + offset); + offset += image_embd.size(); + + // [after_text_embd] + if (n_after > 0) { + std::copy_n(text_result.embeddings.data() + n_before * hidden_size, + n_after * hidden_size, + fused.data() + offset); + } + + LOG_INF("Multimodal fusion: [text:%zu] + [image:%zu] + [text:%zu] = %zu tokens\n", + n_before, n_image, n_after, total); + return fused; +} + +// ============================================================ +// Decode embedding batch into LLM +// (Adapted from mtmd-helper.cpp decode_embd_batch + mtmd_helper_decode_image_chunk) +// Uses normal positional encoding (no M-RoPE, as EP currently only supports LLaVA-Qwen2) +// ============================================================ + +static int decode_embd(llama_context * lctx, + float * embd, + int n_tokens, + int n_embd, + llama_pos & n_past, + int n_batch, + bool logits_last) { + // Allocate auxiliary arrays (managed manually, not via llama_batch_init) + // This follows the same pattern as mtmd-helper.cpp's decode_embd_batch + std::vector pos(n_tokens); + std::vector n_seq_id(n_tokens); + std::vector seq_id_0(n_tokens); + std::vector seq_ids(n_tokens); + std::vector logits(n_tokens, 0); + + for (int i = 0; i < n_tokens; ++i) { + seq_id_0[i] = 0; + seq_ids[i] = &seq_id_0[i]; + } + + int processed = 0; + while (processed < n_tokens) { + int batch_size = std::min(n_batch, n_tokens - processed); + bool is_last_batch = (processed + batch_size >= n_tokens); + + for (int i = 0; i < batch_size; ++i) { + pos[processed + i] = n_past + i; + n_seq_id[processed + i] = 1; + logits[processed + i] = (logits_last && is_last_batch && i == batch_size - 1); + } + + llama_batch batch = { + /*n_tokens =*/ batch_size, + /*token =*/ nullptr, + /*embd =*/ embd + (size_t)processed * n_embd, + /*pos =*/ pos.data() + processed, + /*n_seq_id =*/ n_seq_id.data() + processed, + /*seq_id =*/ seq_ids.data() + processed, + /*logits =*/ logits.data() + processed, + }; + + int ret = llama_decode(lctx, batch); + if (ret != 0) { + LOG_ERR("Failed to decode embedding batch at offset %d\n", processed); + return ret; + } + + n_past += batch_size; + processed += batch_size; + } + return 0; +} + +// ============================================================ +// Context structure +// ============================================================ + +struct mtmd_cli_ep_context { + std::unique_ptr ep_ctx; + common_init_result_ptr llama_init; + + llama_model * model; + llama_context * lctx; + const llama_vocab * vocab; + common_sampler * smpl; + llama_batch batch; + int n_batch; + + // Token embedding matrix for embedding-level fusion + std::vector token_embeddings; + int64_t hidden_size; + + // Pending image binary paths + std::vector pending_images; + + // Chat template + common_chat_templates_ptr tmpls; + std::vector chat_history; + bool use_jinja = false; + + // Legacy template antiprompt + llama_tokens antiprompt_tokens; + + int n_threads = 1; + llama_pos n_past = 0; + + mtmd_cli_ep_context(common_params & params, const std::string & ep_config_dir) + : llama_init(common_init_from_params(params)) + { + model = llama_init->model(); + lctx = llama_init->context(); + vocab = llama_model_get_vocab(model); + smpl = common_sampler_init(model, params.sampling); + n_threads = params.cpuparams.n_threads; + batch = llama_batch_init(1, 0, 1); + n_batch = params.n_batch; + + if (!model || !lctx) { + LOG_ERR("Failed to initialize LLM model\n"); + exit(1); + } + + // Chat template + tmpls = common_chat_templates_init(model, params.chat_template); + use_jinja = params.use_jinja; + chat_history.clear(); + + // Initialize EP vision context + ep_ctx = ep_vision_context::create(ep_config_dir); + hidden_size = ep_ctx->hidden_size(); + + // Load token embeddings + if (!load_token_embeddings(ep_ctx->token_embedding_path(), + ep_ctx->vocab_size(), + hidden_size, + token_embeddings)) { + LOG_ERR("Failed to load token embeddings\n"); + exit(1); + } + + // Validate n_embd matches + int model_n_embd = llama_model_n_embd(model); + LOG_INF("[EP-v2] EP vision engine initialized (hidden_size=%" PRId64 ", model_n_embd=%d, arch=%s)\n", + hidden_size, model_n_embd, ep_ctx->architecture().c_str()); + if (model_n_embd != hidden_size) { + LOG_ERR("FATAL: model n_embd (%d) != EP hidden_size (%" PRId64 ")\n", model_n_embd, hidden_size); + exit(1); + } + + // Antiprompt 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_ep_context() { + llama_batch_free(batch); + common_sampler_free(smpl); + } + + 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() + ); + } + + void add_image(const std::string & binary_path) { + pending_images.push_back(binary_path); + } +}; + +// ============================================================ +// Generate response (reused from mtmd-cli.cpp) +// ============================================================ + +static int generate_response(mtmd_cli_ep_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("\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, token_id, true); + + if (llama_vocab_is_eog(ctx.vocab, token_id) || ctx.check_antiprompt(generated_tokens)) { + LOG("\n"); + break; + } + + LOG("%s", common_token_to_piece(ctx.lctx, token_id).c_str()); + fflush(stdout); + + if (g_is_interrupted) { + LOG("\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; + } + } + + std::string generated_text = common_detokenize(ctx.lctx, generated_tokens); + common_chat_msg msg; + msg.role = "assistant"; + msg.content = generated_text; + ctx.chat_history.push_back(std::move(msg)); + + return 0; +} + +// ============================================================ +// Chat formatting (reused from mtmd-cli.cpp) +// ============================================================ + +static std::string chat_add_and_format(mtmd_cli_ep_context & ctx, common_chat_msg & new_msg) { + auto formatted = common_chat_format_single(ctx.tmpls.get(), ctx.chat_history, + new_msg, new_msg.role == "user", + ctx.use_jinja); + ctx.chat_history.push_back(new_msg); + return formatted; +} + +// ============================================================ +// Eval message - core multimodal processing +// ============================================================ + +static int eval_message_ep(mtmd_cli_ep_context & ctx, common_chat_msg & msg) { + bool add_bos = ctx.chat_history.empty(); + auto formatted_chat = chat_add_and_format(ctx, msg); + bool has_image = !ctx.pending_images.empty(); + + if (g_is_interrupted) return 0; + + if (has_image) { + // === Multimodal path: embedding-level fusion === + + // 1. Replace <__media__> with (EP uses as split marker) + std::string ep_text = formatted_chat; + const std::string mtmd_marker = "<__media__>"; + const std::string ep_marker = ""; + size_t pos = 0; + while ((pos = ep_text.find(mtmd_marker, pos)) != std::string::npos) { + ep_text.replace(pos, mtmd_marker.length(), ep_marker); + pos += ep_marker.length(); + } + + // 2. Encode image using EP ONNX vision engine + LOG_INF("Encoding image with EP vision engine...\n"); + std::vector image_embd = ctx.ep_ctx->encode_image(ctx.pending_images[0]); + LOG_INF("Image encoded: %zu floats (%zu tokens)\n", + image_embd.size(), image_embd.size() / ctx.hidden_size); + + // 3. Encode text (split at , tokenize, look up embeddings) + auto text_result = encode_user_text( + ctx.vocab, ep_text, add_bos, + ctx.token_embeddings, ctx.hidden_size); + + // 4. Fuse embeddings + auto fused = fuse_multimodal_embeddings(image_embd, text_result, ctx.hidden_size); + int n_fused_tokens = fused.size() / ctx.hidden_size; + + // 5. Decode fused embeddings into LLM + int ret = decode_embd(ctx.lctx, fused.data(), n_fused_tokens, + ctx.hidden_size, ctx.n_past, ctx.n_batch, true); + if (ret != 0) { + LOG_ERR("Failed to decode fused embeddings\n"); + return 1; + } + + ctx.pending_images.clear(); + } else { + // === Text-only path === + auto tokens = common_tokenize(ctx.lctx, formatted_chat, add_bos, true); + + // Decode tokens in batches + llama_batch text_batch = llama_batch_init(ctx.n_batch, 0, 1); + size_t i = 0; + while (i < tokens.size()) { + text_batch.n_tokens = 0; + for (; i < tokens.size() && text_batch.n_tokens < ctx.n_batch; i++) { + int32_t j = text_batch.n_tokens; + text_batch.token[j] = tokens[i]; + text_batch.pos[j] = ctx.n_past++; + text_batch.n_seq_id[j] = 1; + text_batch.seq_id[j][0] = 0; + text_batch.logits[j] = (i == tokens.size() - 1); + text_batch.n_tokens++; + } + if (llama_decode(ctx.lctx, text_batch) != 0) { + LOG_ERR("Failed to decode text\n"); + llama_batch_free(text_batch); + return 1; + } + } + llama_batch_free(text_batch); + } + + LOG("\n"); + return 0; +} + +// ============================================================ +// Main function +// ============================================================ + +int main(int argc, char ** argv) { + ggml_time_init(); + + common_params params; + + if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_MTMD, show_additional_info)) { + return 1; + } + + common_init(); + + // Use --mmproj as EP config directory path + std::string ep_config_dir = params.mmproj.path; + if (ep_config_dir.empty()) { + // Fallback: check environment variable + const char * env = std::getenv("EP_CONFIG_DIR"); + if (env) { + ep_config_dir = env; + } + } + if (ep_config_dir.empty()) { + show_additional_info(argc, argv); + LOG_ERR("ERR: Missing --ep-config argument (pass via --mmproj or EP_CONFIG_DIR env)\n"); + return 1; + } + + mtmd_cli_ep_context ctx(params, ep_config_dir); + + 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(console_ctrl_handler), true); +#endif + } + + if (g_is_interrupted) return 130; + + // Evaluate system prompt if present + auto eval_system_prompt_if_present = [&] { + if (params.system_prompt.empty()) { + return 0; + } + common_chat_msg msg; + msg.role = "system"; + msg.content = params.system_prompt; + return eval_message_ep(ctx, msg); + }; + + LOG_WRN("Multimodal CLI with Spacemit EP vision engine\n"); + + if (eval_system_prompt_if_present()) { + return 1; + } + + if (is_single_turn) { + g_is_generating = true; + + // Insert <__media__> marker if not present (same logic as mtmd-cli.cpp) + if (params.prompt.find("<__media__>") == std::string::npos) { + for (size_t i = 0; i < params.image.size(); i++) { + params.prompt = std::string("<__media__>") + params.prompt; + } + } + + common_chat_msg msg; + msg.role = "user"; + msg.content = params.prompt; + + for (const auto & image : params.image) { + ctx.add_image(image); + } + + if (eval_message_ep(ctx, msg)) { + return 1; + } + if (!g_is_interrupted && generate_response(ctx, n_predict)) { + return 1; + } + } else { + // Chat mode + LOG("\n Running in chat mode (EP vision), available commands:"); + LOG("\n /image load a preprocessed image binary"); + LOG("\n /clear clear the chat history"); + LOG("\n /quit or /exit exit the program"); + LOG("\n"); + + std::string content; + + while (!g_is_interrupted) { + g_is_generating = false; + LOG("\n> "); + console::set_display(DISPLAY_TYPE_USER_INPUT); + std::string line; + console::readline(line, false); + if (g_is_interrupted) break; + console::set_display(DISPLAY_TYPE_RESET); + line = string_strip(line); + if (line.empty()) { + continue; + } + if (line == "/quit" || line == "/exit") { + break; + } + if (line == "/clear") { + ctx.n_past = 0; + ctx.chat_history.clear(); + llama_memory_clear(llama_get_memory(ctx.lctx), true); + if (eval_system_prompt_if_present()) { + return 1; + } + LOG("Chat history cleared\n\n"); + continue; + } + g_is_generating = true; + + bool is_image = line == "/image" || line.find("/image ") == 0; + if (is_image) { + if (line.size() < 8) { + LOG_ERR("ERR: Missing image filename\n"); + continue; + } + std::string media_path = line.substr(7); + ctx.add_image(media_path); + LOG("%s image binary loaded\n", media_path.c_str()); + content += "<__media__>"; + continue; + } else { + content += line; + } + + common_chat_msg msg; + msg.role = "user"; + msg.content = content; + int ret = eval_message_ep(ctx, msg); + if (ret) { + return 1; + } + if (g_is_interrupted) break; + if (generate_response(ctx, n_predict)) { + return 1; + } + content.clear(); + } + } + + if (g_is_interrupted) LOG("\nInterrupted by user\n"); + LOG("\n\n"); + llama_perf_context_print(ctx.lctx); + return g_is_interrupted ? 130 : 0; +} From fca6bd2a4e69175d864656748db0b7c805db32c8 Mon Sep 17 00:00:00 2001 From: dengbo Date: Mon, 2 Mar 2026 18:03:09 +0800 Subject: [PATCH 02/40] feat(ggml-profile): add more stage for profile - Add tokenizer stage - Distinguish between prefill and decode phases Change-Id: I397d15937b719e46ec4238b15cbbf87c943a2c63 --- src/llama-context.cpp | 11 +++++++++++ src/llama-vocab.cpp | 6 +++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 3d9714ab1661..7cccabd321c5 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -10,6 +10,7 @@ #include "llama-model.h" #include "llama-ext.h" #include "llama.h" +#include "ggml-profile.h" #include #include @@ -3761,11 +3762,21 @@ int32_t llama_encode( int32_t llama_decode( llama_context * ctx, llama_batch batch) { + // Distinguish between prefill and decode phases + const char * phase_name = (batch.n_tokens > 1) ? "llama_decode_prefill" : "llama_decode_generate"; + + char args[128]; + snprintf(args, sizeof(args), "\"n_tokens\":%d", batch.n_tokens); + + ggml_trace_log_begin(phase_name, "Decode", args); + const int ret = ctx->decode(batch); if (ret != 0 && ret != 1) { LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret); } + ggml_trace_log_end(phase_name, "Decode", NULL); + return ret; } diff --git a/src/llama-vocab.cpp b/src/llama-vocab.cpp index f43cf546ca08..beb5f6b71a39 100644 --- a/src/llama-vocab.cpp +++ b/src/llama-vocab.cpp @@ -1,6 +1,7 @@ #include "llama-vocab.h" #include "ggml.h" +#include "ggml-profile.h" #include "gguf.h" #include "llama-impl.h" #include "llama-model-loader.h" @@ -4090,7 +4091,10 @@ int32_t llama_tokenize( int32_t n_tokens_max, bool add_special, bool parse_special) { - return vocab->tokenize(text, text_len, tokens, n_tokens_max, add_special, parse_special); + ggml_trace_log_begin("llama_tokenize", "Tokenizer", NULL); + int32_t result = vocab->tokenize(text, text_len, tokens, n_tokens_max, add_special, parse_special); + ggml_trace_log_end("llama_tokenize", "Tokenizer", NULL); + return result; } int32_t llama_token_to_piece( From 3ce2522b8446c5770f5a919bfa217f094449db84 Mon Sep 17 00:00:00 2001 From: cailinxi Date: Tue, 3 Mar 2026 07:49:28 +0000 Subject: [PATCH 03/40] mtmd-ep: align image boundary policy and simplify debug paths Change-Id: If472027c8883641e8c3e75e0b0417523428a7c7f --- tools/mtmd/mtmd-cli-ep.cpp | 698 ++++++++++++++++++++++++++----------- 1 file changed, 493 insertions(+), 205 deletions(-) diff --git a/tools/mtmd/mtmd-cli-ep.cpp b/tools/mtmd/mtmd-cli-ep.cpp index 83e12883c9b5..34eaaa247f5e 100644 --- a/tools/mtmd/mtmd-cli-ep.cpp +++ b/tools/mtmd/mtmd-cli-ep.cpp @@ -15,9 +15,10 @@ #include #include #include -#include #include #include +#include +#include #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) #include @@ -37,8 +38,8 @@ static volatile bool g_is_interrupted = false; static void show_additional_info(int /*argc*/, char ** argv) { LOG( "Multimodal CLI with Spacemit EP vision engine\n\n" - "Usage: %s [options] -m --ep-config --image -p \n\n" - " -m and --ep-config are required\n" + "Usage: %s [options] -m --mmproj --image -p \n\n" + " -m and --mmproj are required (or set EP_CONFIG_DIR)\n" " --image and -p are optional, if NOT provided, the CLI will run in chat mode\n", argv[0] ); @@ -61,152 +62,384 @@ static void sigint_handler(int signo) { #endif // ============================================================ -// Token embedding loading and text encoding utilities -// (Adapted from EP's SpineLLMEngine::EncodeUserText) +// Prompt chunking utilities +// text/image are evaluated in order, aligned with mtmd chunk strategy // ============================================================ -static bool load_token_embeddings(const std::string & path, - int64_t vocab_size, - int64_t hidden_size, - std::vector & out) { - const size_t total = vocab_size * hidden_size; - out.resize(total); - std::ifstream file(path, std::ios::binary); - if (!file.is_open()) { - LOG_ERR("Failed to open token embedding file: %s\n", path.c_str()); - return false; +static const std::string k_media_marker = "<__media__>"; +static const std::string k_legacy_image_marker = "<__image__>"; + +static void replace_all(std::string & s, const std::string & from, const std::string & to); +static std::vector split_keep_marker(const std::string & input, const std::string & marker); + +enum class ep_chunk_type { + text, + image, +}; + +struct ep_prompt_chunk { + ep_chunk_type type = ep_chunk_type::text; + std::vector tokens_text; + std::string image_path; +}; + +enum class ep_image_boundary_mode { + native, // follow native mtmd model-family rules + auto_detect, // probe vocab for known token pairs + none, // do not inject image boundary tokens +}; + +enum class ep_media_anchor_mode { + auto_mode, // apply on known architectures for multi-image prompts + on, // always apply for multi-image prompts + off, // disable prompt canonicalization +}; + +static std::string to_lower_ascii(std::string s) { + std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { + return (char)std::tolower(c); + }); + return s; +} + +static ep_image_boundary_mode ep_image_boundary_mode_from_env() { + const char * env = std::getenv("MTMD_EP_IMAGE_BOUNDARY"); + if (env == nullptr || env[0] == '\0') { + return ep_image_boundary_mode::native; + } + + const std::string value = to_lower_ascii(env); + if (value == "native") { + return ep_image_boundary_mode::native; + } + if (value == "auto" || value == "detect") { + return ep_image_boundary_mode::auto_detect; + } + if (value == "none" || value == "off" || value == "0") { + return ep_image_boundary_mode::none; + } + + LOG_WRN("[EP-v3] unknown MTMD_EP_IMAGE_BOUNDARY='%s', fallback to 'native'\n", env); + return ep_image_boundary_mode::native; +} + +static const char * ep_image_boundary_mode_name(ep_image_boundary_mode mode) { + switch (mode) { + case ep_image_boundary_mode::native: return "native"; + case ep_image_boundary_mode::auto_detect: return "auto"; + case ep_image_boundary_mode::none: return "none"; + } + return "native"; +} + +static bool contains_icase(const std::string & text, const std::string & pattern) { + return to_lower_ascii(text).find(to_lower_ascii(pattern)) != std::string::npos; +} + +static ep_media_anchor_mode ep_media_anchor_mode_from_env() { + const char * env = std::getenv("MTMD_EP_MEDIA_ANCHOR"); + if (env == nullptr || env[0] == '\0') { + return ep_media_anchor_mode::off; + } + const std::string value = to_lower_ascii(env); + if (value == "auto") { + return ep_media_anchor_mode::auto_mode; + } + if (value == "on" || value == "1" || value == "true") { + return ep_media_anchor_mode::on; + } + if (value == "off" || value == "0" || value == "false") { + return ep_media_anchor_mode::off; + } + LOG_WRN("[EP-v3] unknown MTMD_EP_MEDIA_ANCHOR='%s', fallback to 'off'\n", env); + return ep_media_anchor_mode::off; +} + +static const char * ep_media_anchor_mode_name(ep_media_anchor_mode mode) { + switch (mode) { + case ep_media_anchor_mode::auto_mode: return "auto"; + case ep_media_anchor_mode::on: return "on"; + case ep_media_anchor_mode::off: return "off"; + } + return "auto"; +} + +static std::vector tokenize_exact_special(llama_context * lctx, const std::string & token_text) { + auto toks = common_tokenize(lctx, token_text, /*add_special*/ false, /*parse_special*/ true); + if (toks.size() != 1) { + return {}; + } + // Ensure this is a true special-token hit, not byte-level fallback. + if (common_token_to_piece(lctx, toks[0]) != token_text) { + return {}; + } + return toks; +} + +static std::pair, std::vector> detect_image_boundary_tokens(llama_context * lctx) { + // Keep order aligned with mtmd.cpp init_vision() common projector families. + static const std::vector> candidates = { + {"<|vision_start|>", "<|vision_end|>"}, + {"<|image_start|>", "<|image_end|>"}, + {"", ""}, + {"", ""}, + {"<|begin_of_image|>", "<|end_of_image|>"}, + {"<|IMAGE_START|>", "<|IMAGE_END|>"}, + {"<|im_start|>", "<|im_end|>"}, + {"", ""}, + }; + + for (const auto & [beg_s, end_s] : candidates) { + auto beg = tokenize_exact_special(lctx, beg_s); + auto end = tokenize_exact_special(lctx, end_s); + if (!beg.empty() && !end.empty()) { + return {std::move(beg), std::move(end)}; + } } - file.read(reinterpret_cast(out.data()), total * sizeof(float)); - if (!file) { - LOG_ERR("Token embedding file incomplete: %s\n", path.c_str()); + return {}; +} + +static bool should_apply_media_anchor(const std::string & arch_name, size_t n_images, ep_media_anchor_mode mode) { + if (n_images < 2) { return false; } - return true; + switch (mode) { + case ep_media_anchor_mode::off: + return false; + case ep_media_anchor_mode::on: + return true; + case ep_media_anchor_mode::auto_mode: + return contains_icase(arch_name, "llavaqwen2forcausallm") || contains_icase(arch_name, "llavaqwen2"); + } + return false; } -// Split text at marker, tokenize both parts, look up token embeddings -struct text_encode_result { - std::vector embeddings; - int n_before = 0; - int n_after = 0; -}; +static std::string canonicalize_multimage_prompt( + const std::string & prompt, + size_t n_images, + const std::string & arch_name, + ep_media_anchor_mode mode, + bool & changed) { + changed = false; + if (!should_apply_media_anchor(arch_name, n_images, mode)) { + return prompt; + } -static text_encode_result encode_user_text( - const llama_vocab * vocab, - const std::string & text, - bool add_bos, - const std::vector & token_embeddings, - int64_t hidden_size) { - text_encode_result result; - - // Split at - std::string before_image, after_image; - size_t image_pos = text.find(""); - if (image_pos != std::string::npos) { - before_image = text.substr(0, image_pos); - size_t after_pos = image_pos + 7; - if (after_pos < text.length() && text[after_pos] == '\n') { - after_pos++; - } - after_image = text.substr(after_pos); - } else { - before_image = text; - } - - // Tokenize before part - std::vector before_tokens(before_image.size() + 64); - int n_before = llama_tokenize(vocab, before_image.c_str(), - static_cast(before_image.length()), - before_tokens.data(), static_cast(before_tokens.size()), - add_bos, true); - if (n_before < 0) { - before_tokens.resize(-n_before); - n_before = llama_tokenize(vocab, before_image.c_str(), - static_cast(before_image.length()), - before_tokens.data(), static_cast(before_tokens.size()), - add_bos, true); - } - before_tokens.resize(n_before); - - // Tokenize after part - std::vector after_tokens; - int n_after = 0; - if (!after_image.empty()) { - after_tokens.resize(after_image.size() + 64); - n_after = llama_tokenize(vocab, after_image.c_str(), - static_cast(after_image.length()), - after_tokens.data(), static_cast(after_tokens.size()), - false, true); - if (n_after < 0) { - after_tokens.resize(-n_after); - n_after = llama_tokenize(vocab, after_image.c_str(), - static_cast(after_image.length()), - after_tokens.data(), static_cast(after_tokens.size()), - false, true); - } - after_tokens.resize(n_after); - } - - result.n_before = n_before; - result.n_after = n_after; - - // Look up token embedding matrix - int total = n_before + n_after; - result.embeddings.resize(total * hidden_size); - - for (int i = 0; i < n_before; ++i) { - const float * src = &token_embeddings[before_tokens[i] * hidden_size]; - float * dst = &result.embeddings[i * hidden_size]; - std::copy_n(src, hidden_size, dst); - } - for (int i = 0; i < n_after; ++i) { - const float * src = &token_embeddings[after_tokens[i] * hidden_size]; - float * dst = &result.embeddings[(n_before + i) * hidden_size]; - std::copy_n(src, hidden_size, dst); - } - - return result; + std::string normalized = prompt; + replace_all(normalized, k_legacy_image_marker, k_media_marker); + + const auto parts = split_keep_marker(normalized, k_media_marker); + size_t marker_count = 0; + for (const auto & p : parts) { + if (p == k_media_marker) { + marker_count++; + } + } + + if (marker_count != n_images || marker_count < 2) { + return normalized; + } + + std::string output; + output.reserve(normalized.size() + marker_count * 48 + 64); + output += "Please align images by order index. "; + output += "Image #1 maps to the first media slot, Image #2 to the second, and so on.\n"; + + size_t image_idx = 0; + for (const auto & part : parts) { + if (part == k_media_marker) { + image_idx++; + output += "[Image "; + output += std::to_string(image_idx); + output += " Begin]\n"; + output += k_media_marker; + output += "\n[Image "; + output += std::to_string(image_idx); + output += " End]\n"; + } else { + output += part; + } + } + + changed = (output != normalized); + return output; } -// ============================================================ -// Multimodal embedding fusion -// [before_text_embd] + [image_embd] + [after_text_embd] -// (Adapted from EP's SpineLLMEngine::MultimodalEmbeddingFusion) -// ============================================================ +static std::pair, std::vector> +detect_image_boundary_tokens_native(llama_context * lctx, const std::string & arch_name) { + // Match native mtmd behavior in mtmd.cpp::init_vision(). + if (contains_icase(arch_name, "qwen2vl") || contains_icase(arch_name, "qwen2_5_vl") || + contains_icase(arch_name, "qwen3vl") || contains_icase(arch_name, "youtuvl")) { + return { + tokenize_exact_special(lctx, "<|vision_start|>"), + tokenize_exact_special(lctx, "<|vision_end|>") + }; + } + if (contains_icase(arch_name, "llama4")) { + return { + tokenize_exact_special(lctx, "<|image_start|>"), + tokenize_exact_special(lctx, "<|image_end|>") + }; + } + if (contains_icase(arch_name, "gemma3")) { + return { + tokenize_exact_special(lctx, ""), + tokenize_exact_special(lctx, "") + }; + } + if (contains_icase(arch_name, "internvl")) { + return { + tokenize_exact_special(lctx, ""), + tokenize_exact_special(lctx, "") + }; + } + if (contains_icase(arch_name, "glm4v")) { + return { + tokenize_exact_special(lctx, "<|begin_of_image|>"), + tokenize_exact_special(lctx, "<|end_of_image|>") + }; + } + if (contains_icase(arch_name, "paddleocr")) { + return { + tokenize_exact_special(lctx, "<|IMAGE_START|>"), + tokenize_exact_special(lctx, "<|IMAGE_END|>") + }; + } + if (contains_icase(arch_name, "lightonocr")) { + return { + tokenize_exact_special(lctx, "<|im_start|>"), + tokenize_exact_special(lctx, "<|im_end|>") + }; + } + return {}; +} -static std::vector fuse_multimodal_embeddings( - const std::vector & image_embd, - const text_encode_result & text_result, - int64_t hidden_size) { - size_t n_image = image_embd.size() / hidden_size; - size_t n_before = text_result.n_before; - size_t n_after = text_result.n_after; - size_t total = n_before + n_image + n_after; - - std::vector fused(total * hidden_size); - size_t offset = 0; - - // [before_text_embd] - std::copy_n(text_result.embeddings.data(), - n_before * hidden_size, - fused.data() + offset); - offset += n_before * hidden_size; - - // [image_embd] - std::copy(image_embd.begin(), image_embd.end(), - fused.data() + offset); - offset += image_embd.size(); - - // [after_text_embd] - if (n_after > 0) { - std::copy_n(text_result.embeddings.data() + n_before * hidden_size, - n_after * hidden_size, - fused.data() + offset); - } - - LOG_INF("Multimodal fusion: [text:%zu] + [image:%zu] + [text:%zu] = %zu tokens\n", - n_before, n_image, n_after, total); - return fused; +static std::pair, std::vector> +resolve_image_boundary_tokens(llama_context * lctx, + const std::string & arch_name, + ep_image_boundary_mode mode) { + if (mode == ep_image_boundary_mode::none) { + return {}; + } + if (mode == ep_image_boundary_mode::auto_detect) { + return detect_image_boundary_tokens(lctx); + } + return detect_image_boundary_tokens_native(lctx, arch_name); +} + +static void replace_all(std::string & s, const std::string & from, const std::string & to) { + if (from.empty()) { + return; + } + size_t pos = 0; + while ((pos = s.find(from, pos)) != std::string::npos) { + s.replace(pos, from.size(), to); + pos += to.size(); + } +} + +static std::vector split_keep_marker(const std::string & input, const std::string & marker) { + std::vector out; + if (input.empty()) { + return out; + } + + size_t start = 0; + while (true) { + size_t pos = input.find(marker, start); + if (pos == std::string::npos) { + out.push_back(input.substr(start)); + break; + } + if (pos > start) { + out.push_back(input.substr(start, pos - start)); + } + out.push_back(marker); + start = pos + marker.size(); + } + return out; +} + +static void append_text_chunk(std::vector & chunks, std::vector && tokens) { + if (tokens.empty()) { + return; + } + if (!chunks.empty() && chunks.back().type == ep_chunk_type::text) { + auto & dst = chunks.back().tokens_text; + dst.insert(dst.end(), tokens.begin(), tokens.end()); + return; + } + + ep_prompt_chunk chunk; + chunk.type = ep_chunk_type::text; + chunk.tokens_text = std::move(tokens); + chunks.emplace_back(std::move(chunk)); +} + +static bool tokenize_to_ep_chunks( + const llama_vocab * vocab, + const std::string & formatted_chat, + bool add_special, + bool parse_special, + const std::vector & image_paths, + std::vector & out_chunks) { + out_chunks.clear(); + + std::string input = formatted_chat; + replace_all(input, k_legacy_image_marker, k_media_marker); + + size_t n_images_used = 0; + const auto parts = split_keep_marker(input, k_media_marker); + for (const auto & part : parts) { + if (part == k_media_marker) { + if (n_images_used >= image_paths.size()) { + LOG_ERR("Number of images (%zu) does not match number of media markers in prompt\n", image_paths.size()); + return false; + } + ep_prompt_chunk chunk; + chunk.type = ep_chunk_type::image; + chunk.image_path = image_paths[n_images_used++]; + out_chunks.emplace_back(std::move(chunk)); + } else { + append_text_chunk(out_chunks, common_tokenize(vocab, part, /*add_special*/ false, parse_special)); + } + } + + if (n_images_used != image_paths.size()) { + LOG_ERR("Number of images (%zu) does not match number of media markers in prompt (%zu)\n", + image_paths.size(), n_images_used); + return false; + } + + if (add_special && llama_vocab_get_add_bos(vocab)) { + const llama_token bos = llama_vocab_bos(vocab); + if (bos != LLAMA_TOKEN_NULL) { + if (!out_chunks.empty() && out_chunks.front().type == ep_chunk_type::text) { + out_chunks.front().tokens_text.insert(out_chunks.front().tokens_text.begin(), bos); + } else { + ep_prompt_chunk bos_chunk; + bos_chunk.type = ep_chunk_type::text; + bos_chunk.tokens_text = { bos }; + out_chunks.insert(out_chunks.begin(), std::move(bos_chunk)); + } + } + } + + if (add_special && llama_vocab_get_add_eos(vocab)) { + const llama_token eos = llama_vocab_eos(vocab); + if (eos != LLAMA_TOKEN_NULL) { + if (!out_chunks.empty() && out_chunks.back().type == ep_chunk_type::text) { + out_chunks.back().tokens_text.push_back(eos); + } else { + ep_prompt_chunk eos_chunk; + eos_chunk.type = ep_chunk_type::text; + eos_chunk.tokens_text = { eos }; + out_chunks.emplace_back(std::move(eos_chunk)); + } + } + } + + return true; } // ============================================================ @@ -268,6 +501,44 @@ static int decode_embd(llama_context * lctx, return 0; } +static int decode_tokens(llama_context * lctx, + const std::vector & tokens, + llama_pos & n_past, + int n_batch, + bool logits_last) { + if (tokens.empty()) { + return 0; + } + + llama_batch batch = llama_batch_init(n_batch, 0, 1); + size_t i = 0; + while (i < tokens.size()) { + batch.n_tokens = 0; + for (; i < tokens.size() && batch.n_tokens < n_batch; ++i) { + const int32_t j = batch.n_tokens; + batch.token[j] = tokens[i]; + batch.pos[j] = n_past + j; + batch.n_seq_id[j] = 1; + batch.seq_id[j][0] = 0; + batch.logits[j] = false; + batch.n_tokens++; + } + + if (logits_last && i == tokens.size()) { + batch.logits[batch.n_tokens - 1] = true; + } + + if (llama_decode(lctx, batch) != 0) { + llama_batch_free(batch); + return 1; + } + n_past += batch.n_tokens; + } + + llama_batch_free(batch); + return 0; +} + // ============================================================ // Context structure // ============================================================ @@ -283,9 +554,11 @@ struct mtmd_cli_ep_context { llama_batch batch; int n_batch; - // Token embedding matrix for embedding-level fusion - std::vector token_embeddings; int64_t hidden_size; + std::vector tok_img_beg; + std::vector tok_img_end; + ep_image_boundary_mode img_boundary_mode = ep_image_boundary_mode::native; + ep_media_anchor_mode media_anchor_mode = ep_media_anchor_mode::off; // Pending image binary paths std::vector pending_images; @@ -325,25 +598,40 @@ struct mtmd_cli_ep_context { // Initialize EP vision context ep_ctx = ep_vision_context::create(ep_config_dir); hidden_size = ep_ctx->hidden_size(); - - // Load token embeddings - if (!load_token_embeddings(ep_ctx->token_embedding_path(), - ep_ctx->vocab_size(), - hidden_size, - token_embeddings)) { - LOG_ERR("Failed to load token embeddings\n"); + img_boundary_mode = ep_image_boundary_mode_from_env(); + media_anchor_mode = ep_media_anchor_mode_from_env(); + if (hidden_size <= 0 || hidden_size > INT_MAX) { + LOG_ERR("FATAL: invalid EP hidden_size (%" PRId64 ")\n", hidden_size); exit(1); } // Validate n_embd matches int model_n_embd = llama_model_n_embd(model); - LOG_INF("[EP-v2] EP vision engine initialized (hidden_size=%" PRId64 ", model_n_embd=%d, arch=%s)\n", + LOG_INF("[EP-v3] EP vision engine initialized (hidden_size=%" PRId64 ", model_n_embd=%d, arch=%s)\n", hidden_size, model_n_embd, ep_ctx->architecture().c_str()); if (model_n_embd != hidden_size) { LOG_ERR("FATAL: model n_embd (%d) != EP hidden_size (%" PRId64 ")\n", model_n_embd, hidden_size); exit(1); } + // Align image boundary tokens with native mtmd behavior by default. + auto boundaries = resolve_image_boundary_tokens(lctx, ep_ctx->architecture(), img_boundary_mode); + tok_img_beg = std::move(boundaries.first); + tok_img_end = std::move(boundaries.second); + LOG_INF("[EP-v3] image boundary mode: %s\n", ep_image_boundary_mode_name(img_boundary_mode)); + LOG_INF("[EP-v3] media anchor mode: %s\n", ep_media_anchor_mode_name(media_anchor_mode)); + if (!tok_img_beg.empty() && !tok_img_end.empty() && + tok_img_beg.front() != LLAMA_TOKEN_NULL && tok_img_end.front() != LLAMA_TOKEN_NULL) { + LOG_INF("[EP-v3] image boundary tokens enabled: beg='%s', end='%s'\n", + common_token_to_piece(lctx, tok_img_beg.front()).c_str(), + common_token_to_piece(lctx, tok_img_end.front()).c_str()); + } else { + LOG_INF("[EP-v3] image boundary tokens disabled for this model (arch=%s)\n", + ep_ctx->architecture().c_str()); + tok_img_beg.clear(); + tok_img_end.clear(); + } + // Antiprompt for legacy templates if (params.chat_template == "vicuna") { antiprompt_tokens = common_tokenize(lctx, "ASSISTANT:", false, true); @@ -438,75 +726,74 @@ static std::string chat_add_and_format(mtmd_cli_ep_context & ctx, common_chat_ms static int eval_message_ep(mtmd_cli_ep_context & ctx, common_chat_msg & msg) { bool add_bos = ctx.chat_history.empty(); + + if (msg.role == "user" && !ctx.pending_images.empty()) { + bool changed = false; + msg.content = canonicalize_multimage_prompt( + msg.content, + ctx.pending_images.size(), + ctx.ep_ctx->architecture(), + ctx.media_anchor_mode, + changed); + if (changed) { + LOG_INF("[EP-v3] media-anchor canonicalization applied (%zu images)\n", ctx.pending_images.size()); + } + } + auto formatted_chat = chat_add_and_format(ctx, msg); - bool has_image = !ctx.pending_images.empty(); if (g_is_interrupted) return 0; - if (has_image) { - // === Multimodal path: embedding-level fusion === - - // 1. Replace <__media__> with (EP uses as split marker) - std::string ep_text = formatted_chat; - const std::string mtmd_marker = "<__media__>"; - const std::string ep_marker = ""; - size_t pos = 0; - while ((pos = ep_text.find(mtmd_marker, pos)) != std::string::npos) { - ep_text.replace(pos, mtmd_marker.length(), ep_marker); - pos += ep_marker.length(); - } - - // 2. Encode image using EP ONNX vision engine - LOG_INF("Encoding image with EP vision engine...\n"); - std::vector image_embd = ctx.ep_ctx->encode_image(ctx.pending_images[0]); - LOG_INF("Image encoded: %zu floats (%zu tokens)\n", - image_embd.size(), image_embd.size() / ctx.hidden_size); - - // 3. Encode text (split at , tokenize, look up embeddings) - auto text_result = encode_user_text( - ctx.vocab, ep_text, add_bos, - ctx.token_embeddings, ctx.hidden_size); - - // 4. Fuse embeddings - auto fused = fuse_multimodal_embeddings(image_embd, text_result, ctx.hidden_size); - int n_fused_tokens = fused.size() / ctx.hidden_size; - - // 5. Decode fused embeddings into LLM - int ret = decode_embd(ctx.lctx, fused.data(), n_fused_tokens, - ctx.hidden_size, ctx.n_past, ctx.n_batch, true); - if (ret != 0) { - LOG_ERR("Failed to decode fused embeddings\n"); + std::vector chunks; + if (!tokenize_to_ep_chunks(ctx.vocab, formatted_chat, add_bos, true, ctx.pending_images, chunks)) { + return 1; + } + + for (size_t i = 0; i < chunks.size(); ++i) { + const bool logits_last = (i == chunks.size() - 1); + const auto & chunk = chunks[i]; + if (chunk.type == ep_chunk_type::text) { + if (decode_tokens(ctx.lctx, chunk.tokens_text, ctx.n_past, ctx.n_batch, logits_last) != 0) { + LOG_ERR("Failed to decode text chunk %zu\n", i); + return 1; + } + continue; + } + + // image chunk + LOG_INF("Encoding image chunk %zu with EP vision engine: %s\n", i, chunk.image_path.c_str()); + std::vector image_embd = ctx.ep_ctx->encode_image(chunk.image_path); + if (image_embd.empty() || image_embd.size() % (size_t)ctx.hidden_size != 0) { + LOG_ERR("Invalid image embedding shape from EP (size=%zu, hidden_size=%" PRId64 ")\n", + image_embd.size(), ctx.hidden_size); return 1; } - ctx.pending_images.clear(); - } else { - // === Text-only path === - auto tokens = common_tokenize(ctx.lctx, formatted_chat, add_bos, true); - - // Decode tokens in batches - llama_batch text_batch = llama_batch_init(ctx.n_batch, 0, 1); - size_t i = 0; - while (i < tokens.size()) { - text_batch.n_tokens = 0; - for (; i < tokens.size() && text_batch.n_tokens < ctx.n_batch; i++) { - int32_t j = text_batch.n_tokens; - text_batch.token[j] = tokens[i]; - text_batch.pos[j] = ctx.n_past++; - text_batch.n_seq_id[j] = 1; - text_batch.seq_id[j][0] = 0; - text_batch.logits[j] = (i == tokens.size() - 1); - text_batch.n_tokens++; + const int n_image_tokens = (int)(image_embd.size() / (size_t)ctx.hidden_size); + if (!ctx.tok_img_beg.empty()) { + if (decode_tokens(ctx.lctx, ctx.tok_img_beg, ctx.n_past, ctx.n_batch, /*logits_last*/ false) != 0) { + LOG_ERR("Failed to decode image-begin token chunk %zu\n", i); + return 1; } - if (llama_decode(ctx.lctx, text_batch) != 0) { - LOG_ERR("Failed to decode text\n"); - llama_batch_free(text_batch); + } + + const bool logits_on_embd = logits_last && ctx.tok_img_end.empty(); + if (decode_embd(ctx.lctx, image_embd.data(), n_image_tokens, + (int)ctx.hidden_size, ctx.n_past, ctx.n_batch, logits_on_embd) != 0) { + LOG_ERR("Failed to decode image chunk %zu\n", i); + return 1; + } + + if (!ctx.tok_img_end.empty()) { + if (decode_tokens(ctx.lctx, ctx.tok_img_end, ctx.n_past, ctx.n_batch, logits_last) != 0) { + LOG_ERR("Failed to decode image-end token chunk %zu\n", i); return 1; } } - llama_batch_free(text_batch); } + ctx.pending_images.clear(); + LOG("\n"); return 0; } @@ -517,6 +804,7 @@ static int eval_message_ep(mtmd_cli_ep_context & ctx, common_chat_msg & msg) { int main(int argc, char ** argv) { ggml_time_init(); + LOG_INF("MTMD_CLI_EP_BUILD_TAG: fastvlm-support-20260303-3 (%s %s)\n", __DATE__, __TIME__); common_params params; @@ -537,7 +825,7 @@ int main(int argc, char ** argv) { } if (ep_config_dir.empty()) { show_additional_info(argc, argv); - LOG_ERR("ERR: Missing --ep-config argument (pass via --mmproj or EP_CONFIG_DIR env)\n"); + LOG_ERR("ERR: Missing EP config directory (pass via --mmproj or EP_CONFIG_DIR env)\n"); return 1; } From b6a460819d30514fa3a279be7e0a9cbdb79717b9 Mon Sep 17 00:00:00 2001 From: cailinxi Date: Thu, 5 Mar 2026 09:30:01 +0000 Subject: [PATCH 04/40] server: add EP vision backend with runtime selection Change-Id: Id1b76f4f497bb6804f38f43acc29b27083f043ba --- common/arg.cpp | 17 + common/common.h | 2 + tools/server/CMakeLists.txt | 37 +++ tools/server/README.md | 20 ++ tools/server/server-common.cpp | 355 +++++++++++++++++---- tools/server/server-common.h | 20 ++ tools/server/server-context.cpp | 184 +++++++++-- tools/server/server-context.h | 1 + tools/server/server-ep-vision.cpp | 513 ++++++++++++++++++++++++++++++ tools/server/server-ep-vision.h | 38 +++ 10 files changed, 1102 insertions(+), 85 deletions(-) create mode 100644 tools/server/server-ep-vision.cpp create mode 100644 tools/server/server-ep-vision.h diff --git a/common/arg.cpp b/common/arg.cpp index 15d5ad77af12..ae762ffc13ed 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -2197,6 +2197,23 @@ common_params_context common_params_parser_init(common_params & params, llama_ex params.mmproj_use_gpu = value; } ).set_examples(mmproj_examples).set_env("LLAMA_ARG_MMPROJ_OFFLOAD")); + add_opt(common_arg( + {"--vision-backend"}, "{auto|mtmd|ep}", + string_format("multimodal backend selection (default: %s)", params.vision_backend.c_str()), + [](common_params & params, const std::string & value) { + if (value != "auto" && value != "mtmd" && value != "ep") { + throw std::invalid_argument("vision-backend must be one of: auto, mtmd, ep"); + } + params.vision_backend = value; + } + ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_VISION_BACKEND")); + add_opt(common_arg( + {"--ep-config-dir"}, "DIR", + "path to EP config directory (config.json + ONNX model files)", + [](common_params & params, const std::string & value) { + params.ep_config_dir = value; + } + ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_EP_CONFIG_DIR")); add_opt(common_arg( {"--image", "--audio"}, "FILE", "path to an image or audio file. use with multimodal models, use comma-separated values for multiple files\n", diff --git a/common/common.h b/common/common.h index 764574e23a09..d92eeb382113 100644 --- a/common/common.h +++ b/common/common.h @@ -556,6 +556,8 @@ struct common_params { struct common_params_model mmproj; bool mmproj_use_gpu = true; // use GPU for multimodal model bool no_mmproj = false; // explicitly disable multimodal model + std::string vision_backend = "auto"; // multimodal backend: auto|mtmd|ep + std::string ep_config_dir; // EP config dir (config.json + ONNX) std::vector image; // path to image file(s) int image_min_tokens = -1; int image_max_tokens = -1; diff --git a/tools/server/CMakeLists.txt b/tools/server/CMakeLists.txt index 2d628704b7be..d2b5d831e36c 100644 --- a/tools/server/CMakeLists.txt +++ b/tools/server/CMakeLists.txt @@ -13,6 +13,8 @@ add_library(${TARGET} STATIC server-queue.h server-common.cpp server-common.h + server-ep-vision.cpp + server-ep-vision.h server-context.cpp server-context.h server-tools.cpp @@ -27,6 +29,41 @@ target_include_directories(${TARGET} PRIVATE ../mtmd) target_include_directories(${TARGET} PRIVATE ${CMAKE_SOURCE_DIR}) target_link_libraries(${TARGET} PUBLIC llama-common mtmd ${CMAKE_THREAD_LIBS_INIT}) +option(LLAMA_SERVER_EP_VISION "Build llama-server with Spacemit EP ONNX vision backend support" OFF) +if(LLAMA_SERVER_EP_VISION) + if(NOT DEFINED SPACEMIT_EP_DIR) + message(FATAL_ERROR "SPACEMIT_EP_DIR must be set when LLAMA_SERVER_EP_VISION=ON") + endif() + if(NOT DEFINED ONNXRUNTIME_INC_DIR) + message(FATAL_ERROR "ONNXRUNTIME_INC_DIR must be set when LLAMA_SERVER_EP_VISION=ON") + endif() + if(NOT DEFINED ONNXRUNTIME_LIB_DIR) + message(FATAL_ERROR "ONNXRUNTIME_LIB_DIR must be set when LLAMA_SERVER_EP_VISION=ON") + endif() + + target_compile_definitions(${TARGET} PRIVATE LLAMA_SERVER_EP_VISION=1) + target_sources(${TARGET} PRIVATE + ../mtmd/ep-vision-wrapper.cpp + ${SPACEMIT_EP_DIR}/src/llm/spine_vision_engine.cc + ${SPACEMIT_EP_DIR}/src/llm/spine_llm_argparser.cc + ) + set(ONNXRUNTIME_LIB "") + if(EXISTS "${ONNXRUNTIME_LIB_DIR}/libonnxruntime.so") + set(ONNXRUNTIME_LIB "${ONNXRUNTIME_LIB_DIR}/libonnxruntime.so") + elseif(EXISTS "${ONNXRUNTIME_LIB_DIR}/libonnxruntime.a") + set(ONNXRUNTIME_LIB "${ONNXRUNTIME_LIB_DIR}/libonnxruntime.a") + else() + message(FATAL_ERROR "Could not find libonnxruntime.{so,a} in ONNXRUNTIME_LIB_DIR='${ONNXRUNTIME_LIB_DIR}'") + endif() + + target_include_directories(${TARGET} PRIVATE + ../mtmd + ${SPACEMIT_EP_DIR}/src/llm + ${ONNXRUNTIME_INC_DIR} + ) + target_link_libraries(${TARGET} PRIVATE ${ONNXRUNTIME_LIB} dl) +endif() + # llama-server executable diff --git a/tools/server/README.md b/tools/server/README.md index 5ba1a58f8c1c..8b25fb39dc38 100644 --- a/tools/server/README.md +++ b/tools/server/README.md @@ -325,6 +325,26 @@ The server includes a set of built-in tools that enable the LLM to access the lo To use this feature, start the server with `--tools all`. You can also enable only specific tools by passing a comma-separated list: `--tools name1,name2,...`. Run `--help` for the full list of available tool names. +### EP vision backend (Spacemit ONNX) + +In addition to the default `mmproj` multimodal backend, `llama-server` can be built with an EP vision backend and selected at runtime: + +- `--vision-backend auto|mtmd|ep` (default: `auto`) +- `--ep-config-dir ` for EP config directory (`config.json` + ONNX model files) + +Selection behavior in `auto` mode: + +- If `--ep-config-dir` is provided, EP is selected. +- Otherwise, if `--mmproj` is provided, mtmd is selected. + +Current EP backend limits: + +- vision-only (audio input is not supported) +- input image data must be preprocessed `.bin` content +- for `image_url`, use either: + - `file://.bin` (requires `--media-path`) + - `data:application/octet-stream;base64,<...>` + ## Build `llama-server` is built alongside everything else from the root of the project diff --git a/tools/server/server-common.cpp b/tools/server/server-common.cpp index 73de0d3bba11..aec2ab1d2f1e 100644 --- a/tools/server/server-common.cpp +++ b/tools/server/server-common.cpp @@ -255,6 +255,12 @@ llama_pos server_tokens::pos_next(int64_t n_tokens) const { if (n_tokens < 0) { llama_pos res = tokens.size(); + if (has_ep) { + for (const auto & it : map_idx_to_ep_media) { + const auto & chunk = it.second; + res += chunk.n_pos - chunk.n_tokens; + } + } else { for (auto it = map_idx_to_media.begin(); it != map_idx_to_media.end(); ++it) { const auto & chunk = it->second; res += mtmd_input_chunk_get_n_pos(chunk.get()) - mtmd_input_chunk_get_n_tokens(chunk.get()); @@ -330,8 +336,14 @@ std::string server_tokens::str() const { } oss << "\n"; oss << "image idx: "; - for (const auto & it : map_idx_to_media) { - oss << it.first << ", "; + if (has_ep) { + for (const auto & it : map_idx_to_ep_media) { + oss << it.first << ", "; + } + } else { + for (const auto & it : map_idx_to_media) { + oss << it.first << ", "; + } } return oss.str(); } @@ -344,6 +356,14 @@ const mtmd::input_chunk_ptr & server_tokens::find_chunk(size_t idx) const { throw std::runtime_error("Chunk not found"); } +const server_ep_image_chunk & server_tokens::find_ep_chunk(size_t idx) const { + auto it = map_idx_to_ep_media.find(idx); + if (it != map_idx_to_ep_media.end()) { + return it->second; + } + throw std::runtime_error("EP chunk not found"); +} + void server_tokens::push_back(llama_token tok) { if (tok == LLAMA_TOKEN_NULL) { throw std::runtime_error("Invalid token"); @@ -373,6 +393,16 @@ void server_tokens::push_back(const mtmd_input_chunk * chunk) { } } +void server_tokens::push_back(const server_ep_image_chunk & chunk) { + GGML_ASSERT(has_mtmd); + has_ep = true; + const size_t start_idx = tokens.size(); + for (int32_t i = 0; i < chunk.n_tokens; ++i) { + tokens.emplace_back(LLAMA_TOKEN_NULL); + } + map_idx_to_ep_media[start_idx] = chunk; +} + void server_tokens::push_back(server_tokens & tokens) { size_t start_idx = size(); for (size_t i = 0; i < tokens.size(); i++) { @@ -382,10 +412,18 @@ void server_tokens::push_back(server_tokens & tokens) { // Assert if we are copying MTMD chunks to a server_tokens that does not have mtmd. // We could also just check, but this will prevent silently dropping MTMD data. GGML_ASSERT(has_mtmd); - for (auto it = tokens.map_idx_to_media.begin(); it != tokens.map_idx_to_media.end(); ) { - auto * chunk = tokens.map_idx_to_media[it->first].get(); - mtmd::input_chunk_ptr new_chunk(mtmd_input_chunk_copy(chunk)); - map_idx_to_media[start_idx + it->first] = std::move(new_chunk); + if (tokens.has_ep) { + has_ep = true; + for (const auto & it : tokens.map_idx_to_ep_media) { + map_idx_to_ep_media[start_idx + it.first] = it.second; + } + } else { + for (auto it = tokens.map_idx_to_media.begin(); it != tokens.map_idx_to_media.end(); ) { + auto * chunk = tokens.map_idx_to_media[it->first].get(); + mtmd::input_chunk_ptr new_chunk(mtmd_input_chunk_copy(chunk)); + map_idx_to_media[start_idx + it->first] = std::move(new_chunk); + ++it; + } } } } @@ -432,16 +470,31 @@ void server_tokens::keep_first(size_t n) { // note that the case where we keep a full image at the end is allowed: // tokens[n - 1] == LLAMA_TOKEN_NULL && tokens[n] != LLAMA_TOKEN_NULL if (tokens[n - 1] == LLAMA_TOKEN_NULL && tokens[n] == LLAMA_TOKEN_NULL) { - find_chunk(n - 1); // will throw an error if the token is not begin-of-chunk + if (has_ep) { + find_ep_chunk(n - 1); // will throw an error if the token is not begin-of-chunk + } else { + find_chunk(n - 1); // will throw an error if the token is not begin-of-chunk + } } } // remove all image chunks that are not used anymore - for (auto it = map_idx_to_media.begin(); it != map_idx_to_media.end(); ) { - size_t idx = it->first; - if (idx >= n) { - it = map_idx_to_media.erase(it); - } else { - ++it; + if (has_ep) { + for (auto it = map_idx_to_ep_media.begin(); it != map_idx_to_ep_media.end(); ) { + size_t idx = it->first; + if (idx >= n) { + it = map_idx_to_ep_media.erase(it); + } else { + ++it; + } + } + } else { + for (auto it = map_idx_to_media.begin(); it != map_idx_to_media.end(); ) { + size_t idx = it->first; + if (idx >= n) { + it = map_idx_to_media.erase(it); + } else { + ++it; + } } } } @@ -474,21 +527,44 @@ size_t server_tokens::get_common_prefix(const server_tokens & b) const { return max_idx; } + if (has_ep != b.has_ep) { + for (size_t i = 0; i < max_idx; ++i) { + if (tokens[i] != b.tokens[i]) { + return i; + } + if (tokens[i] == LLAMA_TOKEN_NULL) { + return i; + } + } + return max_idx; + } + for (size_t i = 0; i < max_idx; ++i) { const llama_token ai = tokens[i]; const llama_token bi = b.tokens[i]; if (ai == LLAMA_TOKEN_NULL && bi == LLAMA_TOKEN_NULL) { - const auto & a_chunk = find_chunk(i); - const auto & b_chunk = b.find_chunk(i); - - GGML_ASSERT(a_chunk && b_chunk); - - const std::string id_ai = mtmd_input_chunk_get_id(a_chunk.get()); - const std::string id_bi = mtmd_input_chunk_get_id(b_chunk.get()); - - const size_t n_tok_a = mtmd_input_chunk_get_n_tokens(a_chunk.get()); - const size_t n_tok_b = mtmd_input_chunk_get_n_tokens(b_chunk.get()); + std::string id_ai; + std::string id_bi; + size_t n_tok_a = 0; + size_t n_tok_b = 0; + + if (has_ep) { + const auto & a_chunk = find_ep_chunk(i); + const auto & b_chunk = b.find_ep_chunk(i); + id_ai = a_chunk.id; + id_bi = b_chunk.id; + n_tok_a = (size_t) a_chunk.n_tokens; + n_tok_b = (size_t) b_chunk.n_tokens; + } else { + const auto & a_chunk = find_chunk(i); + const auto & b_chunk = b.find_chunk(i); + GGML_ASSERT(a_chunk && b_chunk); + id_ai = mtmd_input_chunk_get_id(a_chunk.get()); + id_bi = mtmd_input_chunk_get_id(b_chunk.get()); + n_tok_a = mtmd_input_chunk_get_n_tokens(a_chunk.get()); + n_tok_b = mtmd_input_chunk_get_n_tokens(b_chunk.get()); + } if (id_ai == id_bi && n_tok_a == n_tok_b) { GGML_ASSERT(n_tok_a > 0 && "Invalid media chunk"); // should never happen @@ -518,10 +594,17 @@ bool server_tokens::validate(const struct llama_context * ctx) const { const auto & t = tokens[i]; if (t == LLAMA_TOKEN_NULL) { try { - const auto & chunk = find_chunk(i); - size_t n_tokens = mtmd_input_chunk_get_n_tokens(chunk.get()); - i += n_tokens - 1; // will be +1 by the for loop + size_t n_tokens = 0; + if (has_ep) { + const auto & chunk = find_ep_chunk(i); + n_tokens = (size_t) chunk.n_tokens; + } else { + const auto & chunk = find_chunk(i); + n_tokens = mtmd_input_chunk_get_n_tokens(chunk.get()); + } + i += n_tokens - 1; } catch (const std::exception & e) { + GGML_UNUSED(e); return false; } } else if (t < 0 || t >= n_vocab) { @@ -534,42 +617,77 @@ bool server_tokens::validate(const struct llama_context * ctx) const { int32_t server_tokens::process_chunk( llama_context * ctx, mtmd_context * mctx, + const server_ep_vision_context * ep_ctx, size_t idx, llama_pos pos, int32_t seq_id, size_t & n_tokens_out) const { - const auto & chunk = find_chunk(idx); - const char * name = mtmd_input_chunk_get_type(chunk.get()) == MTMD_INPUT_CHUNK_TYPE_IMAGE - ? "image" : "audio"; - SRV_INF("processing %s...\n", name); - int32_t n_batch = llama_n_batch(ctx); - int64_t t0 = ggml_time_ms(); - llama_pos new_n_past; // unused for now - int32_t result = mtmd_helper_eval_chunk_single(mctx, ctx, - chunk.get(), - pos, - seq_id, - n_batch, - true, // logits last - &new_n_past); - SRV_INF("%s processed in %" PRId64 " ms\n", name, ggml_time_ms() - t0); - if (result != 0) { - LOG_ERR("mtmd_helper_eval failed with status %d", result); - n_tokens_out = 0; - return result; - } - n_tokens_out = mtmd_input_chunk_get_n_tokens(chunk.get()); - return 0; + if (has_ep) { + const auto & chunk = find_ep_chunk(idx); + if (ep_ctx == nullptr) { + n_tokens_out = 0; + return -1; + } + SRV_INF("%s", "processing image (ep)...\n"); + int64_t t0 = ggml_time_ms(); + llama_pos n_past = pos; + int32_t result = server_ep_vision_decode_chunk( + ctx, + ep_ctx, + chunk, + n_past, + seq_id, + llama_n_batch(ctx), + true); + SRV_INF("image (ep) processed in %" PRId64 " ms\n", ggml_time_ms() - t0); + if (result != 0) { + LOG_ERR("server_ep_vision_decode_chunk failed with status %d\n", result); + n_tokens_out = 0; + return result; + } + n_tokens_out = (size_t) chunk.n_tokens; + return 0; + } else { + const auto & chunk = find_chunk(idx); + const char * name = mtmd_input_chunk_get_type(chunk.get()) == MTMD_INPUT_CHUNK_TYPE_IMAGE + ? "image" : "audio"; + SRV_INF("processing %s...\n", name); + int32_t n_batch = llama_n_batch(ctx); + int64_t t0 = ggml_time_ms(); + llama_pos new_n_past; // unused for now + int32_t result = mtmd_helper_eval_chunk_single(mctx, ctx, + chunk.get(), + pos, + seq_id, + n_batch, + true, // logits last + &new_n_past); + SRV_INF("%s processed in %" PRId64 " ms\n", name, ggml_time_ms() - t0); + if (result != 0) { + LOG_ERR("mtmd_helper_eval failed with status %d", result); + n_tokens_out = 0; + return result; + } + n_tokens_out = mtmd_input_chunk_get_n_tokens(chunk.get()); + return 0; + } } server_tokens server_tokens::clone() const { server_tokens res; res.has_mtmd = has_mtmd; + res.has_ep = has_ep; res.tokens = tokens; - for (auto it = map_idx_to_media.begin(); it != map_idx_to_media.end(); ++it) { - size_t idx = it->first; - const mtmd::input_chunk_ptr & chunk = it->second; - res.map_idx_to_media[idx] = mtmd::input_chunk_ptr(mtmd_input_chunk_copy(chunk.get())); + if (has_ep) { + for (const auto & it : map_idx_to_ep_media) { + res.map_idx_to_ep_media[it.first] = it.second; + } + } else { + for (auto it = map_idx_to_media.begin(); it != map_idx_to_media.end(); ++it) { + size_t idx = it->first; + const mtmd::input_chunk_ptr & chunk = it->second; + res.map_idx_to_media[idx] = mtmd::input_chunk_ptr(mtmd_input_chunk_copy(chunk.get())); + } } return res; } @@ -713,6 +831,38 @@ static std::string fnv_hash(const uint8_t * data, size_t len) { return std::to_string(hash); } +static void replace_all(std::string & s, const std::string & from, const std::string & to) { + if (from.empty()) { + return; + } + size_t pos = 0; + while ((pos = s.find(from, pos)) != std::string::npos) { + s.replace(pos, from.size(), to); + pos += to.size(); + } +} + +static std::vector split_keep_marker(const std::string & input, const std::string & marker) { + std::vector out; + size_t pos = 0; + while (true) { + const size_t mpos = input.find(marker, pos); + if (mpos == std::string::npos) { + out.emplace_back(input.substr(pos)); + break; + } + if (mpos > pos) { + out.emplace_back(input.substr(pos, mpos - pos)); + } + out.emplace_back(marker); + pos = mpos + marker.size(); + } + if (out.empty()) { + out.emplace_back(""); + } + return out; +} + server_tokens process_mtmd_prompt(mtmd_context * mctx, std::string prompt, std::vector files) { mtmd::bitmaps bitmaps; for (auto & file : files) { @@ -747,6 +897,60 @@ server_tokens process_mtmd_prompt(mtmd_context * mctx, std::string prompt, std:: return result; } +server_tokens process_ep_prompt( + server_ep_vision_context * ep_ctx, + const llama_vocab * vocab, + std::string prompt, + std::vector files, + bool add_special, + bool parse_special) { + if (ep_ctx == nullptr) { + throw std::runtime_error("EP vision backend is not initialized"); + } + + static const std::string k_media_marker = "<__media__>"; + static const std::string k_legacy_marker = "<__image__>"; + + replace_all(prompt, k_legacy_marker, k_media_marker); + if (!files.empty() && prompt.find(k_media_marker) == std::string::npos) { + for (size_t i = 0; i < files.size(); ++i) { + prompt = k_media_marker + prompt; + } + } + + auto parts = split_keep_marker(prompt, k_media_marker); + size_t marker_count = 0; + for (const auto & p : parts) { + if (p == k_media_marker) { + marker_count++; + } + } + if (marker_count != files.size()) { + throw std::runtime_error("Number of images does not match number of media markers"); + } + + server_tokens out(llama_tokens{}, true); + + size_t img_idx = 0; + bool add_special_once = add_special; + for (const auto & part : parts) { + if (part == k_media_marker) { + auto chunk = server_ep_vision_encode_image_bin(ep_ctx, files[img_idx++]); + out.push_back(chunk); + add_special_once = false; + continue; + } + + auto toks = common_tokenize(vocab, part, add_special_once, parse_special); + for (auto tok : toks) { + out.push_back(tok); + } + add_special_once = false; + } + + return out; +} + /** * break the input "prompt" object into multiple prompt if needed, then tokenize them * use tokenize_input_prompts() if the input could be an array. @@ -756,10 +960,16 @@ server_tokens process_mtmd_prompt(mtmd_context * mctx, std::string prompt, std:: * - "prompt": [12, 34, "string", 56, 78] * - "prompt": { "prompt_string": "string", "multimodal_data": [ "base64" ] } */ -static server_tokens tokenize_input_subprompt(const llama_vocab * vocab, mtmd_context * mctx, const json & json_prompt, bool add_special, bool parse_special) { +static server_tokens tokenize_input_subprompt( + const llama_vocab * vocab, + mtmd_context * mctx, + server_ep_vision_context * ep_ctx, + const json & json_prompt, + bool add_special, + bool parse_special) { constexpr char JSON_STRING_PROMPT_KEY[] = "prompt_string"; constexpr char JSON_MTMD_DATA_KEY[] = "multimodal_data"; - const bool has_mtmd = mctx != nullptr; + const bool has_mtmd = mctx != nullptr || ep_ctx != nullptr; if (json_prompt.is_string() || json_is_array_of_mixed_numbers_strings(json_prompt)) { // string or mixed llama_tokens tmp = tokenize_mixed(vocab, json_prompt, add_special, parse_special); @@ -779,6 +989,9 @@ static server_tokens tokenize_input_subprompt(const llama_vocab * vocab, mtmd_co for (const auto & entry : json_prompt.at(JSON_MTMD_DATA_KEY)) { files.push_back(base64_decode(entry)); } + if (ep_ctx != nullptr) { + return process_ep_prompt(ep_ctx, vocab, json_prompt.at(JSON_STRING_PROMPT_KEY), files, add_special, parse_special); + } return process_mtmd_prompt(mctx, json_prompt.at(JSON_STRING_PROMPT_KEY), files); } else { // Not multimodal, but contains a subobject. @@ -790,15 +1003,21 @@ static server_tokens tokenize_input_subprompt(const llama_vocab * vocab, mtmd_co } } -std::vector tokenize_input_prompts(const llama_vocab * vocab, mtmd_context * mctx, const json & json_prompt, bool add_special, bool parse_special) { +std::vector tokenize_input_prompts( + const llama_vocab * vocab, + mtmd_context * mctx, + server_ep_vision_context * ep_ctx, + const json & json_prompt, + bool add_special, + bool parse_special) { std::vector result; if (json_prompt.is_array() && !json_is_array_and_contains_numbers(json_prompt)) { result.reserve(json_prompt.size()); for (const auto & p : json_prompt) { - result.push_back(tokenize_input_subprompt(vocab, mctx, p,add_special, parse_special)); + result.push_back(tokenize_input_subprompt(vocab, mctx, ep_ctx, p, add_special, parse_special)); } } else { - result.push_back(tokenize_input_subprompt(vocab, mctx, json_prompt, add_special, parse_special)); + result.push_back(tokenize_input_subprompt(vocab, mctx, ep_ctx, json_prompt, add_special, parse_special)); } if (result.empty()) { throw std::runtime_error("\"prompt\" must not be empty"); @@ -853,7 +1072,8 @@ json oaicompat_completion_params_parse(const json & body) { static void handle_media( std::vector & out_files, json & media_obj, - const std::string & media_path) { + const std::string & media_path, + bool image_bin_only) { std::string url = json_value(media_obj, "url", std::string()); if (string_starts_with(url, "http")) { // download remote image @@ -878,6 +1098,9 @@ static void handle_media( } // load local image file std::string file_path = url.substr(7); // remove "file://" + if (image_bin_only && !string_ends_with(file_path, ".bin")) { + throw std::invalid_argument("EP backend expects .bin file for file:// image_url"); + } raw_buffer data; if (!fs_validate_filename(file_path, true)) { throw std::invalid_argument("file path is not allowed: " + file_path); @@ -895,7 +1118,9 @@ static void handle_media( std::vector parts = string_split(url, /*separator*/ ','); if (parts.size() != 2) { throw std::runtime_error("Invalid url value"); - } else if (!string_starts_with(parts[0], "data:image/")) { + } else if (image_bin_only && !string_starts_with(parts[0], "data:application/octet-stream")) { + throw std::runtime_error("EP backend expects data:application/octet-stream;base64"); + } else if (!image_bin_only && !string_starts_with(parts[0], "data:image/")) { throw std::runtime_error("Invalid url format: " + parts[0]); } else if (!string_ends_with(parts[0], "base64")) { throw std::runtime_error("url must be base64 encoded"); @@ -992,11 +1217,11 @@ json oaicompat_chat_params_parse( std::string type = json_value(p, "type", std::string()); if (type == "image_url") { if (!opt.allow_image) { - throw std::runtime_error("image input is not supported - hint: if this is unexpected, you may need to provide the mmproj"); + throw std::runtime_error("image input is not supported - hint: if this is unexpected, you may need to configure multimodal backend"); } json image_url = json_value(p, "image_url", json::object()); - handle_media(out_files, image_url, opt.media_path); + handle_media(out_files, image_url, opt.media_path, opt.image_bin_only); p["type"] = "media_marker"; p["text"] = get_media_marker(); @@ -1004,7 +1229,7 @@ json oaicompat_chat_params_parse( } else if (type == "input_audio") { if (!opt.allow_audio) { - throw std::runtime_error("audio input is not supported - hint: if this is unexpected, you may need to provide the mmproj"); + throw std::runtime_error("audio input is not supported by the active multimodal backend"); } json input_audio = json_value(p, "input_audio", json::object()); @@ -1599,12 +1824,12 @@ server_tokens format_prompt_rerank( std::string prompt = rerank_prompt; string_replace_all(prompt, "{query}" , query); string_replace_all(prompt, "{document}", doc ); - server_tokens tokens = tokenize_input_subprompt(vocab, mctx, prompt, false, true); + server_tokens tokens = tokenize_input_subprompt(vocab, mctx, nullptr, prompt, false, true); result.push_back(tokens); } else { // Get EOS token - use SEP token as fallback if EOS is not available - server_tokens query_tokens = tokenize_input_subprompt(vocab, mctx, query, false, false); - server_tokens doc_tokens = tokenize_input_subprompt(vocab, mctx, doc, false, false); + server_tokens query_tokens = tokenize_input_subprompt(vocab, mctx, nullptr, query, false, false); + server_tokens doc_tokens = tokenize_input_subprompt(vocab, mctx, nullptr, doc, false, false); llama_token eos_token = llama_vocab_eos(vocab); if (eos_token == LLAMA_TOKEN_NULL) { eos_token = llama_vocab_sep(vocab); diff --git a/tools/server/server-common.h b/tools/server/server-common.h index c28558d8b7be..d67c6f1b472d 100644 --- a/tools/server/server-common.h +++ b/tools/server/server-common.h @@ -5,6 +5,7 @@ #include "llama.h" #include "chat.h" #include "mtmd.h" +#include "server-ep-vision.h" #define JSON_ASSERT GGML_ASSERT #include @@ -135,6 +136,9 @@ struct server_tokens { // map a **start** index in tokens to the image chunk // note: the order need to be in-sync with tokens std::map map_idx_to_media; + std::map map_idx_to_ep_media; + + bool has_ep = false; // list of tokens // if the token is LLAMA_TOKEN_NULL, it indicates that this position is occupied by media chunk @@ -179,11 +183,13 @@ struct server_tokens { size_t size_up_to_pos(llama_pos max_pos) const; const mtmd::input_chunk_ptr & find_chunk(size_t idx) const; + const server_ep_image_chunk & find_ep_chunk(size_t idx) const; void push_back(llama_token tok); // will create a copy of the chunk if it contains non-text data void push_back(const mtmd_input_chunk * chunk); + void push_back(const server_ep_image_chunk & chunk); // appends server tokens, updates the media map. copies media chunks. void push_back(server_tokens & tokens); @@ -202,10 +208,13 @@ struct server_tokens { size_t size() const { return tokens.size(); } bool empty() const { return tokens.empty(); } + bool is_ep() const { return has_mtmd && has_ep; } void clear() { map_idx_to_media.clear(); + map_idx_to_ep_media.clear(); tokens.clear(); + has_ep = false; } void keep_first(size_t n); @@ -221,6 +230,7 @@ struct server_tokens { int32_t process_chunk( llama_context * ctx, mtmd_context * mctx, + const server_ep_vision_context * ep_ctx, size_t idx, llama_pos pos, int32_t seq_id, @@ -259,6 +269,13 @@ size_t validate_utf8(const std::string& text); // process mtmd prompt, return the server_tokens containing both text tokens and media chunks server_tokens process_mtmd_prompt(mtmd_context * mctx, std::string prompt, std::vector files); +server_tokens process_ep_prompt( + server_ep_vision_context * ep_ctx, + const llama_vocab * vocab, + std::string prompt, + std::vector files, + bool add_special = true, + bool parse_special = true); /** * break the input "prompt" object into multiple prompt if needed, then tokenize them @@ -276,6 +293,7 @@ server_tokens process_mtmd_prompt(mtmd_context * mctx, std::string prompt, std:: std::vector tokenize_input_prompts( const llama_vocab * vocab, mtmd_context * mctx, + server_ep_vision_context * ep_ctx, const json & json_prompt, bool add_special, bool parse_special); @@ -293,6 +311,8 @@ struct server_chat_params { common_chat_templates_ptr tmpls; bool allow_image; bool allow_audio; + bool image_bin_only = false; + std::string vision_backend = "none"; bool enable_thinking = true; int reasoning_budget = -1; std::string reasoning_budget_message; diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index d49c986feeff..20083c9a7f72 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -5,6 +5,7 @@ #include "server-http.h" #include "server-task.h" #include "server-queue.h" +#include "server-ep-vision.h" #include "build-info.h" #include "common.h" @@ -51,6 +52,12 @@ enum server_state { SERVER_STATE_READY, // Server is ready and model is loaded }; +enum server_vision_backend_mode { + SERVER_VISION_BACKEND_NONE, + SERVER_VISION_BACKEND_MTMD, + SERVER_VISION_BACKEND_EP, +}; + struct server_slot { int id; @@ -611,7 +618,9 @@ struct server_context_impl { llama_model * model_tgt = nullptr; mtmd_context * mctx = nullptr; + server_ep_vision_context * ep_ctx = nullptr; const llama_vocab * vocab = nullptr; + server_vision_backend_mode vision_backend = SERVER_VISION_BACKEND_NONE; server_queue queue_tasks; server_response queue_results; @@ -682,6 +691,19 @@ struct server_context_impl { bool sleeping = false; + bool has_multimodal() const { + return mctx != nullptr || ep_ctx != nullptr; + } + + const char * vision_backend_name() const { + switch (vision_backend) { + case SERVER_VISION_BACKEND_MTMD: return "mtmd"; + case SERVER_VISION_BACKEND_EP: return "ep"; + case SERVER_VISION_BACKEND_NONE: return "none"; + } + return "none"; + } + void destroy() { llama_init.reset(); @@ -690,6 +712,9 @@ struct server_context_impl { mtmd_free(mctx); mctx = nullptr; + server_ep_vision_free(ep_ctx); + ep_ctx = nullptr; + vision_backend = SERVER_VISION_BACKEND_NONE; llama_batch_free(batch); } @@ -782,8 +807,35 @@ struct server_context_impl { params_base.speculative.draft.ctx_dft = ctx_dft.get(); } - std::string & mmproj_path = params_base.mmproj.path; - if (!mmproj_path.empty()) { + const std::string & mmproj_path = params_base.mmproj.path; + const std::string & ep_config_dir = params_base.ep_config_dir; + const std::string & backend_pref = params_base.vision_backend; + + server_vision_backend_mode selected_backend = SERVER_VISION_BACKEND_NONE; + if (backend_pref == "auto") { + if (!ep_config_dir.empty()) { + selected_backend = SERVER_VISION_BACKEND_EP; + } else if (!mmproj_path.empty()) { + selected_backend = SERVER_VISION_BACKEND_MTMD; + } + } else if (backend_pref == "mtmd") { + selected_backend = SERVER_VISION_BACKEND_MTMD; + } else if (backend_pref == "ep") { + selected_backend = SERVER_VISION_BACKEND_EP; + } else { + SRV_ERR("invalid --vision-backend value: '%s'\n", backend_pref.c_str()); + return false; + } + + if (selected_backend == SERVER_VISION_BACKEND_MTMD) { + if (mmproj_path.empty()) { + SRV_ERR("%s", "vision backend 'mtmd' selected but --mmproj is empty\n"); + return false; + } + + if (!is_resume) { + mtmd_helper_log_set(common_log_default_callback, nullptr); + } mtmd_context_params mparams = mtmd_context_params_default(); mparams.use_gpu = params_base.mmproj_use_gpu; @@ -800,8 +852,26 @@ struct server_context_impl { SRV_ERR("failed to load multimodal model, '%s'\n", mmproj_path.c_str()); return false; } - SRV_INF("loaded multimodal model, '%s'\n", mmproj_path.c_str()); + vision_backend = SERVER_VISION_BACKEND_MTMD; + SRV_INF("loaded multimodal model (mtmd), '%s'\n", mmproj_path.c_str()); + } else if (selected_backend == SERVER_VISION_BACKEND_EP) { + if (ep_config_dir.empty()) { + SRV_ERR("%s", "vision backend 'ep' selected but --ep-config-dir is empty\n"); + return false; + } + try { + ep_ctx = server_ep_vision_init(ctx, ep_config_dir); + } catch (const std::exception & e) { + SRV_ERR("failed to load EP vision backend from '%s': %s\n", ep_config_dir.c_str(), e.what()); + return false; + } + vision_backend = SERVER_VISION_BACKEND_EP; + SRV_INF("loaded multimodal model (ep), '%s'\n", ep_config_dir.c_str()); + } else { + vision_backend = SERVER_VISION_BACKEND_NONE; + } + if (has_multimodal()) { if (params_base.ctx_shift) { params_base.ctx_shift = false; SRV_WRN("%s\n", "ctx_shift is not supported by multimodal, it will be disabled"); @@ -889,8 +959,7 @@ struct server_context_impl { slot.n_ctx = n_ctx_slot; slot.mctx = mctx; - slot.prompt.tokens.has_mtmd = mctx != nullptr; - + slot.prompt.tokens.has_mtmd = has_multimodal(); SLT_INF(slot, "new slot, n_ctx = %d\n", slot.n_ctx); slot.callback_on_release = [this](int id_slot) { @@ -1038,8 +1107,10 @@ struct server_context_impl { /* reasoning_format */ params_base.reasoning_format, /* chat_template_kwargs */ params_base.default_template_kwargs, /* tmpls */ std::move(chat_templates), - /* allow_image */ mctx ? mtmd_support_vision(mctx) : false, + /* allow_image */ mctx ? mtmd_support_vision(mctx) : (ep_ctx != nullptr), /* allow_audio */ mctx ? mtmd_support_audio (mctx) : false, + /* image_bin_only */ ep_ctx != nullptr, + /* vision_backend */ vision_backend_name(), /* enable_thinking */ enable_thinking, /* reasoning_budget */ params_base.sampling.reasoning_budget_tokens, /* reasoning_budget_msg */ params_base.sampling.reasoning_budget_message, @@ -1142,6 +1213,12 @@ struct server_context_impl { // cache prompts only for completion tasks update_cache = update_cache && task.type == SERVER_TASK_TYPE_COMPLETION; + // don't update the cache if the slot's context is empty + update_cache = update_cache && tokens.size() > 0; + + // TODO: mtmd does not support prompt cache + update_cache = update_cache && !ret->prompt.tokens.has_mtmd; + if (update_cache) { SRV_INF("%s", "updating prompt cache\n"); @@ -1547,7 +1624,7 @@ struct server_context_impl { // if multimodal is enabled, send an error and return false bool check_no_mtmd(const int id_task) { - if (mctx) { + if (has_multimodal()) { send_error(id_task, "This feature is not supported by multimodal", ERROR_TYPE_NOT_SUPPORTED); return false; } @@ -1741,10 +1818,12 @@ struct server_context_impl { bool tokenize_cli_input(server_task & task) { try { auto & prompt = task.cli_prompt; - if (mctx != nullptr) { + if (ep_ctx != nullptr) { + task.tokens = process_ep_prompt(ep_ctx, vocab, prompt, task.cli_files); + } else if (mctx != nullptr) { task.tokens = process_mtmd_prompt(mctx, prompt, task.cli_files); } else { - task.tokens = std::move(tokenize_input_prompts(vocab, mctx, prompt, true, true)[0]); + task.tokens = std::move(tokenize_input_prompts(vocab, mctx, ep_ctx, prompt, true, true)[0]); } task.cli_prompt.clear(); task.cli_files.clear(); @@ -2162,8 +2241,8 @@ struct server_context_impl { continue; } - if (mctx) { - // we should never reach this because params_base.ctx_shift is automatically disabled if mmproj is loaded + if (has_multimodal()) { + // we should never reach this because params_base.ctx_shift is automatically disabled if multimodal is loaded // we don't support ctx_shift because an image chunk may contains multiple tokens GGML_ABORT("not supported by multimodal"); } @@ -2468,7 +2547,7 @@ struct server_context_impl { size_t head_c = n_past; // cache size_t head_p = n_past; // current prompt - if (mctx) { + if (has_multimodal()) { // we should never reach this GGML_ABORT("not supported by multimodal"); } @@ -2525,7 +2604,9 @@ struct server_context_impl { // the largest pos_min required for a checkpoint to be useful const auto pos_min_thold = std::max(0, pos_next - n_swa); - if (n_past > 0 && n_past < slot.prompt.n_tokens()) { + // note: disallow with multimodal contexts for now + // https://github.com/ggml-org/llama.cpp/issues/17043 + if (!slot.prompt.tokens.has_mtmd && n_past > 0 && n_past < slot.prompt.n_tokens()) { const auto pos_min = llama_memory_seq_pos_min(llama_get_memory(ctx_tgt), slot.id); if (pos_min == -1) { SLT_ERR(slot, "n_past = %d, slot.prompt.tokens.size() = %d, seq_id = %d, pos_min = %d\n", n_past, (int) slot.prompt.tokens.size(), slot.id, pos_min); @@ -2674,6 +2755,32 @@ struct server_context_impl { } } + // check if we should process the image + if (slot.prompt.n_tokens() < slot.task->n_tokens() && input_tokens[slot.prompt.n_tokens()] == LLAMA_TOKEN_NULL) { + // process the image + size_t n_tokens_out = 0; + int32_t res = input_tokens.process_chunk(ctx, mctx, ep_ctx, slot.prompt.n_tokens(), slot.prompt.tokens.pos_next(), slot.id, n_tokens_out); + if (res != 0) { + SLT_ERR(slot, "failed to process image, res = %d\n", res); + send_error(slot, "failed to process image", ERROR_TYPE_SERVER); + slot.release(); + continue; + } + + slot.n_prompt_tokens_processed += n_tokens_out; + + // add the image chunk to cache + { + if (input_tokens.is_ep()) { + const auto & chunk = input_tokens.find_ep_chunk(slot.prompt.n_tokens()); + slot.prompt.tokens.push_back(chunk); // copy + } else { + const auto & chunk = input_tokens.find_chunk(slot.prompt.n_tokens()); + slot.prompt.tokens.push_back(chunk.get()); // copy + } + } + } + // If using an alora, there may be uncached tokens that come // before the invocation sequence. When this happens, the // tokens before the invocation sequence need to be @@ -3289,7 +3396,8 @@ server_context_meta server_context::get_meta() const { /* model_aliases */ impl->model_aliases, /* model_tags */ impl->model_tags, /* model_path */ impl->params_base.model.path, - /* has_mtmd */ impl->mctx != nullptr, + /* vision_backend */ impl->vision_backend_name(), + /* has_mtmd */ impl->has_multimodal(), /* has_inp_image */ impl->chat_params.allow_image, /* has_inp_audio */ impl->chat_params.allow_audio, /* json_webui_settings */ impl->json_webui_settings, @@ -3374,12 +3482,16 @@ std::unique_ptr server_routes::handle_completions_impl( // process prompt std::vector inputs; - if (res_type != TASK_RESPONSE_TYPE_NONE && ctx_server.mctx != nullptr) { - // This is the case used by OAI compatible chat path with MTMD. TODO It can be moved to the path below. - inputs.push_back(process_mtmd_prompt(ctx_server.mctx, prompt.get(), files)); + if (res_type != TASK_RESPONSE_TYPE_NONE && (ctx_server.mctx != nullptr || ctx_server.ep_ctx != nullptr)) { + // OAI-compatible chat path with multimodal backend. + if (ctx_server.ep_ctx != nullptr) { + inputs.push_back(process_ep_prompt(ctx_server.ep_ctx, ctx_server.vocab, prompt.get(), files)); + } else { + inputs.push_back(process_mtmd_prompt(ctx_server.mctx, prompt.get(), files)); + } } else { // Everything else, including multimodal completions. - inputs = tokenize_input_prompts(ctx_server.vocab, ctx_server.mctx, prompt, true, true); + inputs = tokenize_input_prompts(ctx_server.vocab, ctx_server.mctx, ctx_server.ep_ctx, prompt, true, true); } // tasks.reserve(inputs.size()); // TODO: this is inaccurate due to child tasks @@ -3806,6 +3918,7 @@ void server_routes::init_routes() { { "total_slots", params.n_parallel }, { "model_alias", meta->model_name }, { "model_path", meta->model_path }, + { "vision_backend", meta->vision_backend }, { "modalities", json { {"vision", meta->has_inp_image}, {"audio", meta->has_inp_audio}, @@ -3844,6 +3957,35 @@ void server_routes::init_routes() { return res; }; + this->get_api_show = [this](const server_http_req &) { + auto res = create_response(); + std::string tmpl_default = common_chat_templates_source(meta->chat_params.tmpls.get(), ""); + json data = { + { + "model_info", { + { "llama.context_length", meta->slot_n_ctx }, + } + }, + {"modelfile", ""}, + {"parameters", ""}, + {"template", tmpl_default}, + {"details", { + {"parent_model", ""}, + {"format", "gguf"}, + {"family", ""}, + {"families", {""}}, + {"parameter_size", ""}, + {"quantization_level", ""} + }}, + {"model_info", ""}, + {"capabilities", meta->has_mtmd ? json({"completion","multimodal"}) : json({"completion"})}, + {"vision_backend", meta->vision_backend} + }; + + res->ok(data); + return res; + }; + this->post_infill = [this](const server_http_req & req) { auto res = create_response(); // check model compatibility @@ -3899,7 +4041,7 @@ void server_routes::init_routes() { data["input_extra"] = input_extra; // default to empty array if it's not exist std::string prompt = json_value(data, "prompt", std::string()); - std::vector tokenized_prompts = tokenize_input_prompts(ctx_server.vocab, ctx_server.mctx, prompt, false, true); + std::vector tokenized_prompts = tokenize_input_prompts(ctx_server.vocab, ctx_server.mctx, ctx_server.ep_ctx, prompt, false, true); SRV_DBG("creating infill tasks, n_prompts = %d\n", (int) tokenized_prompts.size()); data["prompt"] = format_prompt_infill( ctx_server.vocab, @@ -4076,6 +4218,7 @@ void server_routes::init_routes() { {"description", ""}, {"tags", {""}}, {"capabilities", meta->has_mtmd ? json({"completion","multimodal"}) : json({"completion"})}, + {"vision_backend", meta->vision_backend}, {"parameters", ""}, {"details", { {"parent_model", ""}, @@ -4319,6 +4462,7 @@ json server_routes::get_model_info() const { {"n_embd", meta->model_n_embd_inp}, {"n_params", meta->model_n_params}, {"size", meta->model_size}, + {"vision_backend", meta->vision_backend}, }}, }; } @@ -4460,7 +4604,7 @@ std::unique_ptr server_routes::handle_embeddings_impl(cons } } - auto tokenized_prompts = tokenize_input_prompts(ctx_server.vocab, ctx_server.mctx, prompt, true, true); + auto tokenized_prompts = tokenize_input_prompts(ctx_server.vocab, ctx_server.mctx, ctx_server.ep_ctx, prompt, true, true); for (const auto & tokens : tokenized_prompts) { // this check is necessary for models that do not add BOS token to the input if (tokens.empty()) { diff --git a/tools/server/server-context.h b/tools/server/server-context.h index 58dda891441c..e2fd9d39fc44 100644 --- a/tools/server/server-context.h +++ b/tools/server/server-context.h @@ -18,6 +18,7 @@ struct server_context_meta { std::set model_aliases; std::set model_tags; std::string model_path; + std::string vision_backend; bool has_mtmd; bool has_inp_image; bool has_inp_audio; diff --git a/tools/server/server-ep-vision.cpp b/tools/server/server-ep-vision.cpp new file mode 100644 index 000000000000..287cfa84e6a1 --- /dev/null +++ b/tools/server/server-ep-vision.cpp @@ -0,0 +1,513 @@ +#include "server-ep-vision.h" + +#include "common.h" +#include "log.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(LLAMA_SERVER_EP_VISION) +#include "../mtmd/ep-vision-wrapper.h" +#endif + +#if defined(_WIN32) +#include +#include +#else +#include +#include +#endif + +struct server_ep_vision_context { +#if defined(LLAMA_SERVER_EP_VISION) + std::unique_ptr ep; +#endif + std::mutex mu; + int32_t hidden_size = 0; + bool use_mrope_pos = false; + std::vector tok_img_beg; + std::vector tok_img_end; + std::string architecture; +}; + +static std::string fnv_hash(const uint8_t * data, size_t len) { + const uint64_t fnv_prime = 0x100000001b3ULL; + uint64_t hash = 0xcbf29ce484222325ULL; + for (size_t i = 0; i < len; ++i) { + hash ^= data[i]; + hash *= fnv_prime; + } + return std::to_string(hash); +} + +static std::string to_lower_ascii(std::string s) { + std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { + return (char) std::tolower(c); + }); + return s; +} + +static bool contains_icase(const std::string & text, const std::string & pattern) { + return to_lower_ascii(text).find(to_lower_ascii(pattern)) != std::string::npos; +} + +static bool arch_requires_mrope(const std::string & arch_name) { + return contains_icase(arch_name, "qwen2vl") || + contains_icase(arch_name, "qwen2_5_vl") || + contains_icase(arch_name, "qwen3vl") || + contains_icase(arch_name, "glm4v") || + contains_icase(arch_name, "paddleocr"); +} + +static std::pair infer_image_grid_xy(int32_t n_tokens) { + if (n_tokens <= 0) { + return {0, 0}; + } + + int32_t best_y = 1; + int32_t best_x = n_tokens; + const int32_t root = (int32_t) std::sqrt((double) n_tokens); + for (int32_t y = root; y >= 1; --y) { + if (n_tokens % y == 0) { + best_y = y; + best_x = n_tokens / y; + break; + } + } + return {best_x, best_y}; +} + +static std::vector tokenize_exact_special(llama_context * lctx, const std::string & token_text) { + auto toks = common_tokenize(lctx, token_text, /* add_special */ false, /* parse_special */ true); + if (toks.size() != 1) { + return {}; + } + if (common_token_to_piece(lctx, toks[0]) != token_text) { + return {}; + } + return toks; +} + +static std::pair, std::vector> +detect_image_boundary_tokens_native(llama_context * lctx, const std::string & arch_name) { + if (contains_icase(arch_name, "qwen2vl") || contains_icase(arch_name, "qwen2_5_vl") || + contains_icase(arch_name, "qwen3vl") || contains_icase(arch_name, "youtuvl")) { + return { + tokenize_exact_special(lctx, "<|vision_start|>"), + tokenize_exact_special(lctx, "<|vision_end|>") + }; + } + if (contains_icase(arch_name, "llama4")) { + return { + tokenize_exact_special(lctx, "<|image_start|>"), + tokenize_exact_special(lctx, "<|image_end|>") + }; + } + if (contains_icase(arch_name, "gemma3")) { + return { + tokenize_exact_special(lctx, ""), + tokenize_exact_special(lctx, "") + }; + } + if (contains_icase(arch_name, "internvl")) { + return { + tokenize_exact_special(lctx, ""), + tokenize_exact_special(lctx, "") + }; + } + if (contains_icase(arch_name, "glm4v")) { + return { + tokenize_exact_special(lctx, "<|begin_of_image|>"), + tokenize_exact_special(lctx, "<|end_of_image|>") + }; + } + if (contains_icase(arch_name, "paddleocr")) { + return { + tokenize_exact_special(lctx, "<|IMAGE_START|>"), + tokenize_exact_special(lctx, "<|IMAGE_END|>") + }; + } + if (contains_icase(arch_name, "lightonocr")) { + return { + tokenize_exact_special(lctx, "<|im_start|>"), + tokenize_exact_special(lctx, "<|im_end|>") + }; + } + return {}; +} + +static std::pair, std::vector> +detect_image_boundary_tokens_auto(llama_context * lctx) { + static const std::array, 8> candidates = {{ + {"<|vision_start|>", "<|vision_end|>"}, + {"<|image_start|>", "<|image_end|>"}, + {"", ""}, + {"", ""}, + {"<|begin_of_image|>", "<|end_of_image|>"}, + {"<|IMAGE_START|>", "<|IMAGE_END|>"}, + {"<|im_start|>", "<|im_end|>"}, + {"", ""}, + }}; + + for (const auto & candidate : candidates) { + auto beg = tokenize_exact_special(lctx, candidate.first); + auto end = tokenize_exact_special(lctx, candidate.second); + if (!beg.empty() && !end.empty()) { + return {std::move(beg), std::move(end)}; + } + } + return {}; +} + +enum class ep_image_boundary_mode { + native, + auto_detect, + none, +}; + +static ep_image_boundary_mode ep_image_boundary_mode_from_env() { + const char * env = std::getenv("MTMD_EP_IMAGE_BOUNDARY"); + if (env == nullptr || env[0] == '\0') { + return ep_image_boundary_mode::native; + } + + const std::string value = to_lower_ascii(env); + if (value == "native") { + return ep_image_boundary_mode::native; + } + if (value == "auto" || value == "detect") { + return ep_image_boundary_mode::auto_detect; + } + if (value == "none" || value == "off" || value == "0") { + return ep_image_boundary_mode::none; + } + + LOG_WRN("[server-ep] unknown MTMD_EP_IMAGE_BOUNDARY='%s', fallback to 'native'\n", env); + return ep_image_boundary_mode::native; +} + +static std::pair, std::vector> +resolve_image_boundary_tokens(llama_context * lctx, const std::string & arch_name) { + const auto mode = ep_image_boundary_mode_from_env(); + if (mode == ep_image_boundary_mode::none) { + return {}; + } + if (mode == ep_image_boundary_mode::auto_detect) { + return detect_image_boundary_tokens_auto(lctx); + } + return detect_image_boundary_tokens_native(lctx, arch_name); +} + +static std::string write_temp_bin_file(const std::vector & data) { +#if defined(_WIN32) + char temp_path[MAX_PATH] = {0}; + char temp_file[MAX_PATH] = {0}; + + if (GetTempPathA(MAX_PATH, temp_path) == 0) { + throw std::runtime_error("failed to get temp path"); + } + if (GetTempFileNameA(temp_path, "lse", 0, temp_file) == 0) { + throw std::runtime_error("failed to create temp file"); + } + + FILE * fp = std::fopen(temp_file, "wb"); + if (!fp) { + throw std::runtime_error("failed to open temp file"); + } + const size_t n = std::fwrite(data.data(), 1, data.size(), fp); + std::fclose(fp); + if (n != data.size()) { + std::remove(temp_file); + throw std::runtime_error("failed to write temp file"); + } + return std::string(temp_file); +#else + char tmpl[] = "/tmp/llama-server-ep-XXXXXX"; + const int fd = mkstemp(tmpl); + if (fd < 0) { + throw std::runtime_error("failed to create temp file"); + } + + size_t written = 0; + while (written < data.size()) { + const ssize_t n = write(fd, data.data() + written, data.size() - written); + if (n <= 0) { + close(fd); + std::remove(tmpl); + throw std::runtime_error("failed to write temp file"); + } + written += (size_t) n; + } + close(fd); + return std::string(tmpl); +#endif +} + +static int decode_tokens( + llama_context * lctx, + const std::vector & tokens, + llama_pos & n_past, + int32_t seq_id, + int32_t n_batch, + bool logits_last) { + if (tokens.empty()) { + return 0; + } + + llama_batch batch = llama_batch_init(n_batch, 0, 1); + size_t i = 0; + while (i < tokens.size()) { + batch.n_tokens = 0; + for (; i < tokens.size() && batch.n_tokens < n_batch; ++i) { + const int32_t j = batch.n_tokens; + batch.token[j] = tokens[i]; + batch.pos[j] = n_past + j; + batch.n_seq_id[j] = 1; + batch.seq_id[j][0] = seq_id; + batch.logits[j] = false; + batch.n_tokens++; + } + + if (logits_last && i == tokens.size()) { + batch.logits[batch.n_tokens - 1] = true; + } + + if (llama_decode(lctx, batch) != 0) { + llama_batch_free(batch); + return 1; + } + n_past += batch.n_tokens; + } + + llama_batch_free(batch); + return 0; +} + +static int decode_embd( + llama_context * lctx, + const float * embd, + int32_t n_tokens, + int32_t n_embd, + llama_pos & n_past, + int32_t seq_id, + int32_t n_batch, + bool logits_last, + bool use_mrope_pos, + int32_t nx, + int32_t ny) { + const int n_pos_per_embd = use_mrope_pos ? 4 : 1; + + std::vector pos((size_t) n_tokens * n_pos_per_embd); + std::vector n_seq_id(n_tokens); + std::vector seq_id_0(n_tokens); + std::vector seq_ids(n_tokens); + std::vector logits(n_tokens, 0); + + for (int i = 0; i < n_tokens; ++i) { + seq_id_0[i] = seq_id; + seq_ids[i] = &seq_id_0[i]; + } + + if (use_mrope_pos) { + if (nx > 0 && ny > 0 && nx * ny == n_tokens) { + for (int y = 0; y < ny; ++y) { + for (int x = 0; x < nx; ++x) { + const int i = y * nx + x; + pos[(size_t) i] = n_past; + pos[(size_t) i + n_tokens] = n_past + y; + pos[(size_t) i + 2 * n_tokens] = n_past + x; + pos[(size_t) i + 3 * n_tokens] = 0; + } + } + } else { + for (int i = 0; i < n_tokens; ++i) { + pos[(size_t) i] = n_past + i; + pos[(size_t) i + n_tokens] = n_past + i; + pos[(size_t) i + 2 * n_tokens] = n_past + i; + pos[(size_t) i + 3 * n_tokens] = 0; + } + } + } else { + for (int i = 0; i < n_tokens; ++i) { + pos[(size_t) i] = n_past + i; + } + } + + int processed = 0; + while (processed < n_tokens) { + const int batch_size = std::min(n_batch, n_tokens - processed); + const bool is_last_batch = processed + batch_size >= n_tokens; + + for (int i = 0; i < batch_size; ++i) { + if (!use_mrope_pos) { + pos[processed + i] = n_past + processed + i; + } + n_seq_id[processed + i] = 1; + logits[processed + i] = (logits_last && is_last_batch && i == batch_size - 1); + } + + llama_pos * pos_ptr = nullptr; + std::vector pos_view; + if (use_mrope_pos) { + pos_view.reserve((size_t) batch_size * n_pos_per_embd); + for (int d = 0; d < n_pos_per_embd; ++d) { + const size_t src_idx = (size_t) d * n_tokens + processed; + pos_view.insert(pos_view.end(), pos.data() + src_idx, pos.data() + src_idx + batch_size); + } + pos_ptr = pos_view.data(); + } else { + pos_ptr = pos.data() + processed; + } + + llama_batch batch = { + /* n_tokens */ batch_size, + /* token */ nullptr, + /* embd */ const_cast(embd + (size_t) processed * n_embd), + /* pos */ pos_ptr, + /* n_seq_id */ n_seq_id.data() + processed, + /* seq_id */ seq_ids.data() + processed, + /* logits */ logits.data() + processed, + }; + + if (llama_decode(lctx, batch) != 0) { + return 1; + } + processed += batch_size; + } + + if (use_mrope_pos) { + n_past += std::max(nx, ny); + } else { + n_past += n_tokens; + } + + return 0; +} + +server_ep_vision_context * server_ep_vision_init( + llama_context * lctx, + const std::string & config_dir) { +#if defined(LLAMA_SERVER_EP_VISION) + auto ctx = std::make_unique(); + ctx->ep = ep_vision_context::create(config_dir); + ctx->architecture = ctx->ep->architecture(); + ctx->hidden_size = (int32_t) ctx->ep->hidden_size(); + ctx->use_mrope_pos = arch_requires_mrope(ctx->architecture); + + auto boundaries = resolve_image_boundary_tokens(lctx, ctx->architecture); + ctx->tok_img_beg = std::move(boundaries.first); + ctx->tok_img_end = std::move(boundaries.second); + + LOG_INF("[server-ep] initialized (hidden_size=%d, arch=%s, mrope=%s)\n", + ctx->hidden_size, + ctx->architecture.c_str(), + ctx->use_mrope_pos ? "on" : "off"); + return ctx.release(); +#else + GGML_UNUSED(lctx); + GGML_UNUSED(config_dir); + throw std::runtime_error("EP vision backend is not compiled. Rebuild with LLAMA_SERVER_EP_VISION=ON."); +#endif +} + +void server_ep_vision_free(server_ep_vision_context * ctx) { + delete ctx; +} + +server_ep_image_chunk server_ep_vision_encode_image_bin( + server_ep_vision_context * ctx, + const std::vector & data) { + if (ctx == nullptr) { + throw std::runtime_error("EP context is null"); + } + +#if defined(LLAMA_SERVER_EP_VISION) + std::lock_guard lock(ctx->mu); + const std::string tmp_file = write_temp_bin_file(data); + + server_ep_image_chunk out; + try { + out.embd = ctx->ep->encode_image(tmp_file); + std::remove(tmp_file.c_str()); + } catch (...) { + std::remove(tmp_file.c_str()); + throw; + } + + if (ctx->hidden_size <= 0 || out.embd.empty() || out.embd.size() % (size_t) ctx->hidden_size != 0) { + throw std::runtime_error("Invalid EP embedding shape"); + } + + const int32_t n_image_tokens = (int32_t) (out.embd.size() / (size_t) ctx->hidden_size); + auto grid = infer_image_grid_xy(n_image_tokens); + + const int32_t n_pos_img = ctx->use_mrope_pos ? std::max(grid.first, grid.second) : n_image_tokens; + out.n_tokens = (int32_t) ctx->tok_img_beg.size() + n_image_tokens + (int32_t) ctx->tok_img_end.size(); + out.n_pos = (int32_t) ctx->tok_img_beg.size() + n_pos_img + (int32_t) ctx->tok_img_end.size(); + out.grid_nx = grid.first; + out.grid_ny = grid.second; + out.id = fnv_hash(data.data(), data.size()); + + return out; +#else + GGML_UNUSED(data); + throw std::runtime_error("EP vision backend is not compiled. Rebuild with LLAMA_SERVER_EP_VISION=ON."); +#endif +} + +int32_t server_ep_vision_decode_chunk( + llama_context * lctx, + const server_ep_vision_context * ctx, + const server_ep_image_chunk & chunk, + llama_pos & n_past, + int32_t seq_id, + int32_t n_batch, + bool logits_last) { + if (ctx == nullptr) { + return -1; + } + + const int32_t n_image_tokens = (int32_t) (chunk.embd.size() / (size_t) ctx->hidden_size); + if (n_image_tokens <= 0) { + return -1; + } + + if (!ctx->tok_img_beg.empty()) { + if (decode_tokens(lctx, ctx->tok_img_beg, n_past, seq_id, n_batch, false) != 0) { + return -1; + } + } + + const bool logits_on_embd = logits_last && ctx->tok_img_end.empty(); + if (decode_embd( + lctx, + chunk.embd.data(), + n_image_tokens, + ctx->hidden_size, + n_past, + seq_id, + n_batch, + logits_on_embd, + ctx->use_mrope_pos, + chunk.grid_nx, + chunk.grid_ny) != 0) { + return -1; + } + + if (!ctx->tok_img_end.empty()) { + if (decode_tokens(lctx, ctx->tok_img_end, n_past, seq_id, n_batch, logits_last) != 0) { + return -1; + } + } + + return 0; +} diff --git a/tools/server/server-ep-vision.h b/tools/server/server-ep-vision.h new file mode 100644 index 000000000000..3ca750f74300 --- /dev/null +++ b/tools/server/server-ep-vision.h @@ -0,0 +1,38 @@ +#pragma once + +#include "llama.h" + +#include +#include +#include + +struct server_ep_image_chunk { + std::string id; + std::vector embd; + + int32_t n_tokens = 0; + int32_t n_pos = 0; + int32_t grid_nx = 0; + int32_t grid_ny = 0; +}; + +struct server_ep_vision_context; + +server_ep_vision_context * server_ep_vision_init( + llama_context * lctx, + const std::string & config_dir); + +void server_ep_vision_free(server_ep_vision_context * ctx); + +server_ep_image_chunk server_ep_vision_encode_image_bin( + server_ep_vision_context * ctx, + const std::vector & data); + +int32_t server_ep_vision_decode_chunk( + llama_context * lctx, + const server_ep_vision_context * ctx, + const server_ep_image_chunk & chunk, + llama_pos & n_past, + int32_t seq_id, + int32_t n_batch, + bool logits_last); From ea645ce90b8155d3d70be5164673daf8fda8b5ff Mon Sep 17 00:00:00 2001 From: cailinxi Date: Thu, 5 Mar 2026 09:30:17 +0000 Subject: [PATCH 05/40] mtmd: update EP cli flow and add qwen3vl preprocess docs Change-Id: If6bc429163e5122161efb29aef1fe058cc95b73c --- docs/multimodal/llama-mtmd-cli-ep.md | 433 +++++++++++++++++++++++++++ tools/mtmd/mtmd-cli-ep.cpp | 111 ++++++- tools/mtmd/preprocess_qwen3vl.py | 386 ++++++++++++++++++++++++ 3 files changed, 921 insertions(+), 9 deletions(-) create mode 100644 docs/multimodal/llama-mtmd-cli-ep.md create mode 100644 tools/mtmd/preprocess_qwen3vl.py diff --git a/docs/multimodal/llama-mtmd-cli-ep.md b/docs/multimodal/llama-mtmd-cli-ep.md new file mode 100644 index 000000000000..783dd6e7d1c2 --- /dev/null +++ b/docs/multimodal/llama-mtmd-cli-ep.md @@ -0,0 +1,433 @@ +# llama-mtmd-cli-ep 使用文档 + +`llama-mtmd-cli-ep` 是基于 `llama.cpp` 的多模态命令行推理工具,专为 Spacemit EP ONNX 视觉引擎设计。 + +- **文本推理**:由 llama.cpp 加载 GGUF 格式的文本模型完成 +- **视觉编码**:由 Spacemit EP ONNX 引擎完成,读取预处理的图像二进制文件(`.bin`) +- **运行模式**:支持单轮推理和交互聊天两种模式 + +> **状态说明(重要)**: +> 目前仅在 **FastVLM** 与 **Qwen3VL** 方案上做过端到端实测。文档中其它“架构匹配”内容仅表示代码里存在对应 token 匹配逻辑,不代表已经过完整验证。 + +--- + +## 目录 + +- [1. 与原生 llama-mtmd-cli 的区别](#1-与原生-llama-mtmd-cli-的区别) +- [2. 前置条件](#2-前置条件) +- [3. 命令行参数说明](#3-命令行参数说明) +- [4. 单轮推理模式](#4-单轮推理模式) +- [5. 交互聊天模式](#5-交互聊天模式) +- [6. 环境变量](#6-环境变量) +- [7. 验证范围与兼容性说明](#7-验证范围与兼容性说明) +- [8. 板端运行建议](#8-板端运行建议) +- [9. 常见报错与排查](#9-常见报错与排查) +- [10. 当前限制](#10-当前限制) + +--- + +## 1. 与原生 llama-mtmd-cli 的区别 + +| 对比项 | 原生 `llama-mtmd-cli` | EP 版 `llama-mtmd-cli-ep` | +|--------|----------------------|--------------------------| +| `--mmproj` 指向 | `mmproj.gguf` 文件 | EP 配置目录(含 `config.json` + ONNX 模型) | +| `--image` 格式 | jpg / png 等常见图片格式 | 预处理后的二进制文件(`.bin`) | +| 视觉编码后端 | CLIP/GGUF | Spacemit EP ONNX 引擎 | +| 音频支持 | 支持 | 不支持(仅视觉) | + +--- + +## 2. 前置条件 + +运行前需要准备以下文件: + +1. **文本模型**(GGUF 格式) + - 已验证示例:`fastvlm-text-0.5B-Q4_1.gguf`、`qwen3vl-30b-text-q4_1.gguf` + +2. **EP 视觉配置目录**,目录内至少包含: + - `config.json`:视觉模型配置,其中的 `hidden_size` **必须**与文本模型的 `n_embd` 一致 + - 视觉 ONNX 模型文件(如 `fastvlm_vision.f16.onnx`、`qwen3_vl_vision.q_replaceneg.onnx`) + +3. **预处理后的图像二进制文件** + - 例如 `input.bin`、`input2.bin` + - 这些文件由外部预处理工具生成,不是原始的 jpg/png + +> **注意**:如果 `config.json` 中的 `hidden_size` 与文本模型的 `n_embd` 不一致,程序会报错并退出。 + +--- + +## 3. 命令行参数说明 + +### 3.1 必需参数 + +| 参数 | 格式 | 说明 | +|------|------|------| +| `-m` | `-m ` | 文本模型文件路径(GGUF 格式)。这是 LLM 推理的核心模型。 | +| `--mmproj` (或 `-mm`) | `--mmproj <目录路径>` | EP 视觉配置目录路径,目录内需包含 `config.json` 和 ONNX 视觉模型。也可通过环境变量 `EP_CONFIG_DIR` 替代。 | + +### 3.2 模式控制参数 + +| 参数 | 格式 | 说明 | +|------|------|------| +| `--image` | `--image ` | 预处理的图像二进制文件路径。支持两种方式指定多个图像:① 逗号分隔 `--image a.bin,b.bin`;② 重复参数 `--image a.bin --image b.bin`。当与 `-p` 同时提供时进入**单轮推理模式**。 | +| `-p` | `-p "<提示词>"` | 用户提示词。在提示词中使用 `<__media__>` 标记图像插入位置。当与 `--image` 同时提供时进入**单轮推理模式**。 | + +> 当 `--image` 和 `-p` **同时提供**时为单轮推理模式;否则进入交互聊天模式。 + +### 3.3 生成控制参数 + +| 参数 | 格式 | 说明 | +|------|------|------| +| `-n` | `-n <数量>` | 最大生成 token 数量。默认 `-1` 表示不限制(生成到 EOS 或手动中断)。 | +| `--temp` | `--temp <温度值>` | 采样温度,控制生成随机性。值越高输出越随机,值越低越确定。 | +| `--top-k` | `--top-k ` | Top-K 采样参数。 | +| `--top-p` | `--top-p

` | Top-P(核采样)参数。 | + +### 3.4 上下文与模板参数 + +| 参数 | 格式 | 说明 | +|------|------|------| +| `-c` | `-c <大小>` | 上下文窗口大小(token 数)。 | +| `-b` | `-b <批大小>` | 批处理大小,影响推理吞吐。 | +| `-t` | `-t <线程数>` | 推理使用的 CPU 线程数。 | +| `--chat-template` | `--chat-template <名称>` | 指定聊天模板名称。如不指定,使用模型内置模板。 | +| `--system-prompt` | `--system-prompt "<文本>"` | 系统提示词。会在对话开始前作为 system 角色消息注入。 | +| `--jinja` | `--jinja` | 启用 Jinja 模板渲染聊天格式。 | + +### 3.5 关于 `<__media__>` 标记 + +`<__media__>` 是提示词中的图像占位标记,用于指定图像嵌入的插入位置: + +- 每个 `<__media__>` 按顺序对应一个 `--image` 指定的图像文件 +- `<__media__>` 的数量**必须**与图像文件数量一致 +- 如果提示词中未包含 `<__media__>`,程序会自动在提示词前面为每张图像添加一个 +- 旧标记 `<__image__>` 仍然兼容,会被自动替换为 `<__media__>` + +--- + +## 4. 单轮推理模式 + +### 4.1 触发条件 + +同时提供 `--image` 和 `-p` 参数时,进入单轮推理模式。程序处理完一次请求后自动退出。 + +### 4.2 基本用法 + +```bash +llama-mtmd-cli-ep \ + -m <模型文件.gguf> \ + --mmproj \ + --image <图像.bin> \ + -p "<提示词>" \ + -n <最大token数> +``` + +### 4.3 单图推理示例 + +```bash +llama-mtmd-cli-ep \ + -m ./multimodal_llm_files/fastvlm-text-0.5B-Q4_1.gguf \ + --mmproj ./multimodal_llm_files \ + --image ./multimodal_llm_files/input.bin \ + -p "<__media__>请描述这张图片的内容" \ + -n 128 +``` + +提示词中的 `<__media__>` 会被替换为 `input.bin` 编码后的图像嵌入。如果省略 `<__media__>`,程序会自动在提示词前面插入。 + +### 4.4 多图推理示例 + +多图推理时,`<__media__>` 数量必须与图像数量一致。 + +**方式 A:逗号分隔图像路径** + +```bash +llama-mtmd-cli-ep \ + -m ./multimodal_llm_files/fastvlm-text-0.5B-Q4_1.gguf \ + --mmproj ./multimodal_llm_files \ + --image ./multimodal_llm_files/input.bin,./multimodal_llm_files/input2.bin \ + -p "<__media__>先描述第一张图片,再结合<__media__>比较第二张图片的差异" \ + -n 256 +``` + +**方式 B:重复 `--image` 参数** + +```bash +llama-mtmd-cli-ep \ + -m ./multimodal_llm_files/fastvlm-text-0.5B-Q4_1.gguf \ + --mmproj ./multimodal_llm_files \ + --image ./multimodal_llm_files/input.bin \ + --image ./multimodal_llm_files/input2.bin \ + -p "<__media__>先描述第一张图片,再结合<__media__>比较第二张图片的差异" \ + -n 256 +``` + +### 4.5 带系统提示词的推理 + +```bash +llama-mtmd-cli-ep \ + -m ./multimodal_llm_files/fastvlm-text-0.5B-Q4_1.gguf \ + --mmproj ./multimodal_llm_files \ + --image ./multimodal_llm_files/input.bin \ + --system-prompt "你是一个专业的图像分析助手,请用中文详细描述图片内容。" \ + -p "<__media__>请分析这张图" \ + -n 256 +``` + +### 4.6 处理流程 + +1. 加载文本模型和 EP 视觉引擎 +2. 如果有系统提示词,先评估系统消息 +3. 检查提示词中是否包含 `<__media__>`,如果没有则自动在前面为每张图片添加 +4. 将提示词按 `<__media__>` 分割为文本块和图像块 +5. 依次处理每个块: + - **文本块**:tokenize 后送入 LLM 解码 + - **图像块**:通过 EP 视觉引擎编码为嵌入向量,注入图像边界 token 后送入 LLM +6. 采样生成响应,直到遇到 EOS token 或达到最大 token 数 +7. 输出响应并退出 + +--- + +## 5. 交互聊天模式 + +### 5.1 触发条件 + +当 `--image` 和 `-p` **未同时提供**时,进入交互聊天模式。程序显示提示符 `>` 等待用户输入。 + +### 5.2 启动命令 + +```bash +llama-mtmd-cli-ep \ + -m ./multimodal_llm_files/fastvlm-text-0.5B-Q4_1.gguf \ + --mmproj ./multimodal_llm_files +``` + +启动后会显示: + +``` +Running in chat mode (EP vision), available commands: + /image load a preprocessed image binary + /clear clear the chat history + /quit or /exit exit the program +``` + +### 5.3 聊天命令 + +| 命令 | 说明 | +|------|------| +| `/image ` | 加载一个预处理的图像二进制文件,并在当前输入中追加一个 `<__media__>` 标记。可以在发送文本前多次使用来加载多张图片。 | +| `/clear` | 清空聊天历史和上下文,恢复到初始状态。如有系统提示词会重新评估。 | +| `/quit` 或 `/exit` | 退出程序。 | +| `Ctrl+C` | 中断当前生成。再按一次 `Ctrl+C` 退出程序。 | +| 其他文本 | 作为用户消息发送给模型,触发模型生成响应。 | + +### 5.4 交互示例 + +#### 纯文本聊天 + +``` +> 你好,请介绍一下你自己 +你好!我是一个多模态AI助手,可以理解文本和图像... + +> 1+1等于几? +1+1等于2。 +``` + +#### 图文聊天(先加载图片,再提问) + +``` +> /image ./multimodal_llm_files/input.bin +./multimodal_llm_files/input.bin image binary loaded + +> 请描述这张图片的内容 +这张图片展示了... + +> 图片中有几个人? +图片中有... +``` + +#### 多图聊天 + +``` +> /image ./multimodal_llm_files/input.bin +./multimodal_llm_files/input.bin image binary loaded + +> /image ./multimodal_llm_files/input2.bin +./multimodal_llm_files/input2.bin image binary loaded + +> 比较这两张图片的区别 +第一张图片...第二张图片... + +> /clear +Chat history cleared +``` + +### 5.5 聊天模式工作流程 + +1. 用户输入 `/image `:图像路径加入待处理队列,`<__media__>` 标记追加到当前消息内容 +2. 用户输入普通文本:文本追加到当前消息内容,触发推理 +3. 推理时将消息通过聊天模板格式化,分块处理文本和图像 +4. 生成的响应存入聊天历史,支持多轮上下文 +5. `/clear` 会清空聊天历史和 KV Cache,重新开始对话 + +--- + +## 6. 环境变量 + +### 6.1 `EP_CONFIG_DIR` + +当未通过 `--mmproj` 指定 EP 配置目录时,程序会尝试从此环境变量读取。 + +```bash +export EP_CONFIG_DIR=./multimodal_llm_files +llama-mtmd-cli-ep -m text.gguf --image input.bin -p "描述图片" +``` + +### 6.2 `MTMD_EP_IMAGE_BOUNDARY` + +控制图像边界 token 的注入策略。图像边界 token(如 `<|vision_start|>` / `<|vision_end|>`)用于告诉 LLM 图像嵌入的起止位置。 + +| 值 | 说明 | +|----|------| +| `native`(默认,推荐) | 根据模型架构名称(如 qwen2vl、gemma3 等)自动匹配对应的边界 token | +| `auto` 或 `detect` | 不依赖架构名称,尝试从词汇表中探测已知的边界 token 对 | +| `none`、`off` 或 `0` | 不注入任何图像边界 token | + +```bash +export MTMD_EP_IMAGE_BOUNDARY=native +``` + +### 6.3 `MTMD_EP_MEDIA_ANCHOR` + +控制多图提示词的锚点规范化。启用后会为多图提示词自动添加图像编号标注,帮助模型区分多张图片。 + +| 值 | 说明 | +|----|------| +| `off`(默认) | 不进行规范化 | +| `auto` | 仅对已知支持的架构(如 LLaVA-Qwen2)应用规范化 | +| `on`、`1` 或 `true` | 对所有多图提示词强制应用规范化 | + +规范化效果示例: + +``` +# 原始提示词: +<__media__>先描述第一张,再结合<__media__>比较第二张差异 + +# 规范化后: +Please align images by order index. Image #1 maps to the first media slot, Image #2 to the second, and so on. +[Image 1 Begin] +<__media__> +[Image 1 End] +先描述第一张,再结合 +[Image 2 Begin] +<__media__> +[Image 2 End] +比较第二张差异 +``` + +--- + +## 7. 验证范围与兼容性说明 + +### 7.1 已完成端到端验证的模型 + +当前仅验证了以下两类方案: + +| 方案 | `config.json` 中常见 `architectures` | 状态 | +|------|--------------------------------------|------| +| FastVLM | `LlavaQwen2ForCausalLM` | 已验证 | +| Qwen3VL | `Qwen3VL` | 已验证 | + +### 7.2 图像边界 token 匹配规则(代码层) + +EP 版工具会根据文本模型架构名称匹配图像边界 token。下表表示**代码中存在匹配逻辑**,不等同于“已完成端到端验证”: + +| 模型架构 | 图像开始 token | 图像结束 token | +|---------|---------------|---------------| +| Qwen2-VL / Qwen2.5-VL / Qwen3-VL / YoutuVL | `<\|vision_start\|>` | `<\|vision_end\|>` | +| Llama4 | `<\|image_start\|>` | `<\|image_end\|>` | +| Gemma3 | `` | `` | +| InternVL | `` | `` | +| GLM-4V | `<\|begin_of_image\|>` | `<\|end_of_image\|>` | +| PaddleOCR | `<\|IMAGE_START\|>` | `<\|IMAGE_END\|>` | +| LightonOCR | `<\|im_start\|>` | `<\|im_end\|>` | + +如果你的模型架构不在上面列表中,可以尝试设置 `MTMD_EP_IMAGE_BOUNDARY=auto` 让程序自动探测,或设置为 `none` 跳过边界 token 注入。 + +> 对于未验证模型,建议先做小样本功能验证(单图、短上下文、固定提示词),再进行批量测试。 + +--- + +## 8. 板端运行建议 + +### 8.1 设置动态库路径 + +```bash +export LD_LIBRARY_PATH=./llamainstall/lib/:ort_installed/lib/:installed/lib/ +``` + +### 8.2 记录运行日志 + +建议将输出保存到日志文件,方便调试: + +```bash +LOG_FILE=./ep_run_$(date +%Y%m%d_%H%M%S).log +llama-mtmd-cli-ep \ + -m ./multimodal_llm_files/fastvlm-text-0.5B-Q4_1.gguf \ + --mmproj ./multimodal_llm_files \ + --image ./multimodal_llm_files/input.bin \ + -p "<__media__>请描述这张图" \ + -n 128 \ + 2>&1 | tee "$LOG_FILE" +``` + +### 8.3 推理性能调优 + +- `-t <线程数>`:根据板端 CPU 核心数设置合理的线程数 +- `-b <批大小>`:增大批大小可以提高吞吐,但会增加内存占用 +- `-c <上下文大小>`:根据需要调整上下文窗口大小,减小可以节省内存 + +--- + +## 9. 常见报错与排查 + +### `Missing EP config directory` + +**原因**:未通过 `--mmproj` 指定 EP 配置目录,且环境变量 `EP_CONFIG_DIR` 也未设置。 + +**解决**:添加 `--mmproj <目录路径>` 或设置 `export EP_CONFIG_DIR=<目录路径>`。 + +### `Number of images (...) does not match number of media markers (...)` + +**原因**:提示词中 `<__media__>` 标记的数量与 `--image` 指定的图像文件数量不一致。 + +**解决**:确保每张图片对应一个 `<__media__>` 标记。例如两张图片需要两个 `<__media__>`。 + +### `model n_embd (...) != EP hidden_size (...)` + +**原因**:文本模型的嵌入维度与 EP 配置中的 `hidden_size` 不匹配。 + +**解决**:使用同一套模型导出的文本 GGUF 和 EP 视觉配置。 + +### `Invalid image embedding shape from EP` + +**原因**:EP 视觉引擎对图像的编码输出形状不正确。可能是 `.bin` 文件格式或来源不正确,或视觉 ONNX 模型文件有问题。 + +**解决**:检查 `.bin` 文件是否由正确的预处理工具生成,且与当前的 ONNX 视觉模型匹配。 + +### `Failed to decode token` / `Failed to decode text chunk` + +**原因**:LLM 解码过程中出错,可能是上下文窗口溢出或内存不足。 + +**解决**:尝试增大 `-c` 上下文大小,或减少输入图片数量。 + +--- + +## 10. 当前限制 + +- 仅支持视觉输入(图像),**不支持音频输入** +- 图像输入必须是预处理后的二进制文件(`.bin`),不能直接使用 jpg/png +- 端到端仅在 FastVLM、Qwen3VL 上实测通过;其它模型请视为“未验证状态” +- 建议使用默认的环境变量配置以保持稳定: + - `MTMD_EP_IMAGE_BOUNDARY=native` + - `MTMD_EP_MEDIA_ANCHOR=off` diff --git a/tools/mtmd/mtmd-cli-ep.cpp b/tools/mtmd/mtmd-cli-ep.cpp index 34eaaa247f5e..b3dee3952eaf 100644 --- a/tools/mtmd/mtmd-cli-ep.cpp +++ b/tools/mtmd/mtmd-cli-ep.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) @@ -136,6 +137,33 @@ static bool contains_icase(const std::string & text, const std::string & pattern return to_lower_ascii(text).find(to_lower_ascii(pattern)) != std::string::npos; } +static bool arch_requires_mrope(const std::string & arch_name) { + return contains_icase(arch_name, "qwen2vl") || + contains_icase(arch_name, "qwen2_5_vl") || + contains_icase(arch_name, "qwen3vl") || + contains_icase(arch_name, "glm4v") || + contains_icase(arch_name, "paddleocr"); +} + +static std::pair infer_image_grid_xy(int n_tokens) { + if (n_tokens <= 0) { + return {0, 0}; + } + + // Choose the factor pair closest to square to approximate (nx, ny). + int best_y = 1; + int best_x = n_tokens; + int root = (int) std::sqrt((double) n_tokens); + for (int y = root; y >= 1; --y) { + if (n_tokens % y == 0) { + best_y = y; + best_x = n_tokens / y; + break; + } + } + return {best_x, best_y}; +} + static ep_media_anchor_mode ep_media_anchor_mode_from_env() { const char * env = std::getenv("MTMD_EP_MEDIA_ANCHOR"); if (env == nullptr || env[0] == '\0') { @@ -445,7 +473,7 @@ static bool tokenize_to_ep_chunks( // ============================================================ // Decode embedding batch into LLM // (Adapted from mtmd-helper.cpp decode_embd_batch + mtmd_helper_decode_image_chunk) -// Uses normal positional encoding (no M-RoPE, as EP currently only supports LLaVA-Qwen2) +// Supports both normal positional encoding and M-RoPE positional layout. // ============================================================ static int decode_embd(llama_context * lctx, @@ -454,10 +482,14 @@ static int decode_embd(llama_context * lctx, int n_embd, llama_pos & n_past, int n_batch, - bool logits_last) { - // Allocate auxiliary arrays (managed manually, not via llama_batch_init) - // This follows the same pattern as mtmd-helper.cpp's decode_embd_batch - std::vector pos(n_tokens); + bool logits_last, + bool use_mrope_pos, + int nx, + int ny) { + const int n_pos_per_embd = use_mrope_pos ? 4 : 1; + + // Allocate auxiliary arrays (managed manually, not via llama_batch_init). + std::vector pos((size_t) n_tokens * n_pos_per_embd); std::vector n_seq_id(n_tokens); std::vector seq_id_0(n_tokens); std::vector seq_ids(n_tokens); @@ -468,22 +500,63 @@ static int decode_embd(llama_context * lctx, seq_ids[i] = &seq_id_0[i]; } + if (use_mrope_pos) { + if (nx > 0 && ny > 0 && nx * ny == n_tokens) { + for (int y = 0; y < ny; ++y) { + for (int x = 0; x < nx; ++x) { + const int i = y * nx + x; + pos[(size_t) i] = n_past; + pos[(size_t) i + n_tokens] = n_past + y; + pos[(size_t) i + 2 * n_tokens] = n_past + x; + pos[(size_t) i + 3 * n_tokens] = 0; + } + } + } else { + // Fallback to 1D M-RoPE-style positions if grid inference is inconsistent. + for (int i = 0; i < n_tokens; ++i) { + pos[(size_t) i] = n_past + i; + pos[(size_t) i + n_tokens] = n_past + i; + pos[(size_t) i + 2 * n_tokens] = n_past + i; + pos[(size_t) i + 3 * n_tokens] = 0; + } + } + } else { + for (int i = 0; i < n_tokens; ++i) { + pos[(size_t) i] = n_past + i; + } + } + int processed = 0; while (processed < n_tokens) { int batch_size = std::min(n_batch, n_tokens - processed); bool is_last_batch = (processed + batch_size >= n_tokens); for (int i = 0; i < batch_size; ++i) { - pos[processed + i] = n_past + i; + if (!use_mrope_pos) { + pos[processed + i] = n_past + processed + i; + } n_seq_id[processed + i] = 1; logits[processed + i] = (logits_last && is_last_batch && i == batch_size - 1); } + llama_pos * pos_ptr = nullptr; + std::vector pos_view; + if (use_mrope_pos) { + pos_view.reserve((size_t) batch_size * n_pos_per_embd); + for (int d = 0; d < n_pos_per_embd; ++d) { + const size_t src_idx = (size_t) d * n_tokens + processed; + pos_view.insert(pos_view.end(), pos.data() + src_idx, pos.data() + src_idx + batch_size); + } + pos_ptr = pos_view.data(); + } else { + pos_ptr = pos.data() + processed; + } + llama_batch batch = { /*n_tokens =*/ batch_size, /*token =*/ nullptr, /*embd =*/ embd + (size_t)processed * n_embd, - /*pos =*/ pos.data() + processed, + /*pos =*/ pos_ptr, /*n_seq_id =*/ n_seq_id.data() + processed, /*seq_id =*/ seq_ids.data() + processed, /*logits =*/ logits.data() + processed, @@ -495,9 +568,15 @@ static int decode_embd(llama_context * lctx, return ret; } - n_past += batch_size; processed += batch_size; } + + if (use_mrope_pos) { + n_past += std::max(nx, ny); + } else { + n_past += n_tokens; + } + return 0; } @@ -555,6 +634,7 @@ struct mtmd_cli_ep_context { int n_batch; int64_t hidden_size; + bool use_mrope_pos = false; std::vector tok_img_beg; std::vector tok_img_end; ep_image_boundary_mode img_boundary_mode = ep_image_boundary_mode::native; @@ -598,6 +678,7 @@ struct mtmd_cli_ep_context { // Initialize EP vision context ep_ctx = ep_vision_context::create(ep_config_dir); hidden_size = ep_ctx->hidden_size(); + use_mrope_pos = arch_requires_mrope(ep_ctx->architecture()); img_boundary_mode = ep_image_boundary_mode_from_env(); media_anchor_mode = ep_media_anchor_mode_from_env(); if (hidden_size <= 0 || hidden_size > INT_MAX) { @@ -620,6 +701,7 @@ struct mtmd_cli_ep_context { tok_img_end = std::move(boundaries.second); LOG_INF("[EP-v3] image boundary mode: %s\n", ep_image_boundary_mode_name(img_boundary_mode)); LOG_INF("[EP-v3] media anchor mode: %s\n", ep_media_anchor_mode_name(media_anchor_mode)); + LOG_INF("[EP-v3] mrope decode mode: %s\n", use_mrope_pos ? "enabled" : "disabled"); if (!tok_img_beg.empty() && !tok_img_end.empty() && tok_img_beg.front() != LLAMA_TOKEN_NULL && tok_img_end.front() != LLAMA_TOKEN_NULL) { LOG_INF("[EP-v3] image boundary tokens enabled: beg='%s', end='%s'\n", @@ -770,6 +852,16 @@ static int eval_message_ep(mtmd_cli_ep_context & ctx, common_chat_msg & msg) { } const int n_image_tokens = (int)(image_embd.size() / (size_t)ctx.hidden_size); + int grid_nx = n_image_tokens; + int grid_ny = 1; + if (ctx.use_mrope_pos) { + auto grid_xy = infer_image_grid_xy(n_image_tokens); + grid_nx = grid_xy.first; + grid_ny = grid_xy.second; + LOG_INF("[EP-v3] inferred image token grid: nx=%d, ny=%d, n_tokens=%d\n", + grid_nx, grid_ny, n_image_tokens); + } + if (!ctx.tok_img_beg.empty()) { if (decode_tokens(ctx.lctx, ctx.tok_img_beg, ctx.n_past, ctx.n_batch, /*logits_last*/ false) != 0) { LOG_ERR("Failed to decode image-begin token chunk %zu\n", i); @@ -779,7 +871,8 @@ static int eval_message_ep(mtmd_cli_ep_context & ctx, common_chat_msg & msg) { const bool logits_on_embd = logits_last && ctx.tok_img_end.empty(); if (decode_embd(ctx.lctx, image_embd.data(), n_image_tokens, - (int)ctx.hidden_size, ctx.n_past, ctx.n_batch, logits_on_embd) != 0) { + (int)ctx.hidden_size, ctx.n_past, ctx.n_batch, logits_on_embd, + ctx.use_mrope_pos, grid_nx, grid_ny) != 0) { LOG_ERR("Failed to decode image chunk %zu\n", i); return 1; } diff --git a/tools/mtmd/preprocess_qwen3vl.py b/tools/mtmd/preprocess_qwen3vl.py new file mode 100644 index 000000000000..6a51b54ae728 --- /dev/null +++ b/tools/mtmd/preprocess_qwen3vl.py @@ -0,0 +1,386 @@ +#!/usr/bin/env python3 +""" +Qwen3-VL / Qwen2-VL / Qwen2.5-VL 图像预处理脚本 + +将 jpg/png 图像转换为 llama-mtmd-cli-ep 所需的 float32 二进制文件 (.bin)。 +等效于 llama.cpp 中 clip.cpp 的 clip_image_preprocess (PROJECTOR_TYPE_QWEN3VL 分支) +和 set_input (HWC -> CHW 转换)。 + +用法: + python preprocess_qwen3vl.py input.jpg output.bin [--onnx-model vision.onnx] + python preprocess_qwen3vl.py input.jpg output.bin --size 448x448 + python preprocess_qwen3vl.py input.jpg output.bin --min-pixels 3136 --max-pixels 12544 + +输出格式: float32, NCHW 排布 [1, 3, H, W], 直接用于 EP ONNX 视觉模型输入。 +""" + +import argparse +import math +import sys + +import numpy as np +from PIL import Image + + +# ============================================================ +# Qwen VL 默认归一化参数 (与 HuggingFace preprocessor_config.json 一致) +# 实际值存储在 mmproj GGUF 中,这里用标准 CLIP 值作为默认 +# ============================================================ + +DEFAULT_IMAGE_MEAN = [0.48145466, 0.4578275, 0.40821073] +DEFAULT_IMAGE_STD = [0.26862954, 0.26130258, 0.27577711] + +# Qwen VL 系列默认参数 +DEFAULT_PATCH_SIZE = 14 +DEFAULT_MERGE_SIZE = 2 +DEFAULT_MIN_TOKENS = 4 +DEFAULT_MAX_TOKENS = 16384 + + +# ============================================================ +# Smart Resize (等效于 clip.cpp calc_size_preserved_ratio) +# ============================================================ + +def smart_resize(height: int, width: int, align_size: int, + min_pixels: int, max_pixels: int) -> tuple[int, int]: + """ + 保持宽高比的智能缩放,确保: + - 输出 H 和 W 都是 align_size 的整数倍 + - min_pixels <= H*W <= max_pixels + """ + def round_by_factor(x): + return round(x / align_size) * align_size + + def ceil_by_factor(x): + return math.ceil(x / align_size) * align_size + + def floor_by_factor(x): + return math.floor(x / align_size) * align_size + + # 先按 align_size 四舍五入对齐 + h_bar = max(align_size, round_by_factor(height)) + w_bar = max(align_size, round_by_factor(width)) + + # 如果超过 max_pixels,缩小 + if h_bar * w_bar > max_pixels: + beta = math.sqrt(height * width / max_pixels) + h_bar = max(align_size, floor_by_factor(height / beta)) + w_bar = max(align_size, floor_by_factor(width / beta)) + # 如果小于 min_pixels,放大 + elif h_bar * w_bar < min_pixels: + beta = math.sqrt(min_pixels / (height * width)) + h_bar = ceil_by_factor(height * beta) + w_bar = ceil_by_factor(width * beta) + + return h_bar, w_bar + + +# ============================================================ +# 从 ONNX 模型读取输入 shape (可选) +# ============================================================ + +def get_onnx_input_shape(onnx_path: str) -> tuple[int, ...] | None: + """从 ONNX 模型的第一个输入读取静态 shape""" + try: + import onnx + model = onnx.load(onnx_path, load_external_data=False) + inp = model.graph.input[0] + dims = [] + for d in inp.type.tensor_type.shape.dim: + if d.dim_value > 0: + dims.append(d.dim_value) + else: + return None # 包含动态维度 + return tuple(dims) + except ImportError: + print("警告: 未安装 onnx 包,无法读取模型输入 shape", file=sys.stderr) + return None + except Exception as e: + print(f"警告: 读取 ONNX 模型失败: {e}", file=sys.stderr) + return None + + +def get_onnx_output_token_count(onnx_path: str) -> int | None: + """读取 ONNX 首个输出的 token 维度(若为静态)""" + try: + import onnx + model = onnx.load(onnx_path, load_external_data=False) + out = model.graph.output[0] + dims = [] + for d in out.type.tensor_type.shape.dim: + if d.dim_value > 0: + dims.append(d.dim_value) + else: + return None + + # 常见输出: [tokens, hidden] 或 [1, tokens, hidden] + if len(dims) == 2: + return int(dims[0]) + if len(dims) == 3 and dims[0] == 1: + return int(dims[1]) + return None + except Exception: + return None + + +def _load_onnx_constants(onnx_path: str) -> dict[str, np.ndarray] | None: + """读取 ONNX 中 Constant 节点和 initializer 的常量值""" + try: + import onnx + from onnx import numpy_helper + + model = onnx.load(onnx_path, load_external_data=False) + const_map: dict[str, np.ndarray] = {} + + for node in model.graph.node: + if node.op_type != "Constant": + continue + for attr in node.attribute: + if attr.name == "value": + const_map[node.output[0]] = numpy_helper.to_array(attr.t) + + for init in model.graph.initializer: + const_map[init.name] = numpy_helper.to_array(init) + + return const_map + except Exception: + return None + + +def _is_127_5_const(arr: np.ndarray) -> bool: + arr = np.asarray(arr, dtype=np.float32) + return arr.size > 0 and np.allclose(arr, 127.5, atol=1e-4, rtol=0) + + +def onnx_has_internal_1275_norm(onnx_path: str) -> bool: + """ + 检测 ONNX 是否内置 (x - 127.5) / 127.5 归一化。 + 命中后应关闭外部归一化,直接输出 0..255 的 float32 像素。 + """ + try: + import onnx + + model = onnx.load(onnx_path, load_external_data=False) + const_map = _load_onnx_constants(onnx_path) + if not const_map: + return False + + nodes = list(model.graph.node) + check_n = min(64, len(nodes)) + for i in range(check_n): + node = nodes[i] + if node.op_type != "Sub": + continue + + sub_const = None + for inp in node.input: + if inp in const_map and _is_127_5_const(const_map[inp]): + sub_const = inp + break + if sub_const is None: + continue + + sub_out = node.output[0] + for j in range(i + 1, min(i + 12, check_n)): + node2 = nodes[j] + if node2.op_type != "Div": + continue + if sub_out in node2.input and sub_const in node2.input: + return True + + return False + except Exception: + return False + + +# ============================================================ +# 主处理流程 +# ============================================================ + +def preprocess(image_path: str, output_path: str, + target_h: int | None = None, target_w: int | None = None, + patch_size: int = DEFAULT_PATCH_SIZE, + merge_size: int = DEFAULT_MERGE_SIZE, + min_tokens: int = DEFAULT_MIN_TOKENS, + max_tokens: int = DEFAULT_MAX_TOKENS, + image_mean: list[float] = None, + image_std: list[float] = None, + onnx_model: str | None = None, + norm_mode: str = "auto"): + """ + 预处理流程: + 1. 读取图像并转为 RGB + 2. Smart Resize (保持宽高比, 对齐到 align_size) + 3. 归一化(可选): + - external: (pixel/255 - mean) / std + - none: 直接使用 0..255 float32 像素(适用于 ONNX 内置归一化) + - auto: 若检测到 ONNX 内置 (x-127.5)/127.5,则使用 none,否则 external + 4. HWC -> NCHW + 5. 写入 float32 二进制文件 + """ + if image_mean is None: + image_mean = DEFAULT_IMAGE_MEAN + if image_std is None: + image_std = DEFAULT_IMAGE_STD + + # 1. 读取图像 + img = Image.open(image_path).convert("RGB") + orig_w, orig_h = img.size + print(f"原始图像大小: {orig_w}x{orig_h}") + + # 2. 确定目标尺寸 + if onnx_model: + shape = get_onnx_input_shape(onnx_model) + if shape is not None and len(shape) == 4: + _, _, target_h, target_w = shape + print(f"从 ONNX 模型读取输入 shape: {shape}") + + if target_h is not None and target_w is not None: + new_h, new_w = target_h, target_w + print(f"使用指定尺寸: {new_w}x{new_h}") + else: + align_size = patch_size * merge_size + pixel_per_token = patch_size * patch_size * merge_size * merge_size + min_pixels = min_tokens * pixel_per_token + max_pixels = max_tokens * pixel_per_token + new_h, new_w = smart_resize(orig_h, orig_w, align_size, min_pixels, max_pixels) + print(f"Smart Resize: {new_w}x{new_h} " + f"(align={align_size}, pixels={new_h*new_w}, " + f"range=[{min_pixels}, {max_pixels}])") + + # 3. Resize (双线性插值, 与 clip.cpp RESIZE_ALGO_BILINEAR 一致) + img_resized = img.resize((new_w, new_h), Image.BILINEAR) + + effective_norm_mode = norm_mode + if norm_mode == "auto": + if onnx_model and onnx_has_internal_1275_norm(onnx_model): + effective_norm_mode = "none" + else: + effective_norm_mode = "external" + + # 4. 转为 numpy 并按模式处理 + pixels_u8 = np.array(img_resized, dtype=np.float32) # [H, W, 3], 0..255 + if effective_norm_mode == "external": + pixels_01 = pixels_u8 / 255.0 + mean = np.array(image_mean, dtype=np.float32).reshape(1, 1, 3) + std = np.array(image_std, dtype=np.float32).reshape(1, 1, 3) + processed = (pixels_01 - mean) / std # [H, W, 3] + else: + processed = pixels_u8 # [H, W, 3], 0..255 float32 + + # 5. HWC -> NCHW (等效于 clip.cpp 第 3616-3632 行的转换) + # clip.cpp 内存布局: [R_plane, G_plane, B_plane] 即 CHW + # EP ONNX 模型输入通常为 [1, 3, H, W] 即 NCHW + chw = processed.transpose(2, 0, 1) # [3, H, W] + nchw = chw.reshape(1, 3, new_h, new_w) # [1, 3, H, W] + + # 6. 写入 float32 二进制文件 + data = nchw.astype(np.float32).tobytes() + with open(output_path, "wb") as f: + f.write(data) + + n_tokens = None + if onnx_model: + n_tokens = get_onnx_output_token_count(onnx_model) + if n_tokens is None: + n_tokens = (new_h // patch_size // merge_size) * (new_w // patch_size // merge_size) + print(f"输出文件: {output_path}") + print(f"归一化模式: {effective_norm_mode}") + print(f"数据格式: float32, shape=[1, 3, {new_h}, {new_w}]") + print(f"文件大小: {len(data)} bytes ({len(data) // 4} floats)") + print(f"数值范围: min={nchw.min():.6f}, max={nchw.max():.6f}") + print(f"预计图像 token 数: {n_tokens}") + + +def parse_size(s: str) -> tuple[int, int]: + """解析 WxH 或 HxW 格式的尺寸字符串""" + parts = s.lower().split("x") + if len(parts) != 2: + raise argparse.ArgumentTypeError(f"无效的尺寸格式: {s}, 应为 WxH (如 448x448)") + return int(parts[1]), int(parts[0]) # 返回 (H, W) + + +def main(): + parser = argparse.ArgumentParser( + description="Qwen3-VL 图像预处理: 将 jpg/png 转为 EP ONNX 引擎所需的 .bin 文件", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=""" +示例: + # 自动 smart_resize (推荐) + python preprocess_qwen3vl.py photo.jpg photo.bin + + # 指定固定尺寸 (宽x高) + python preprocess_qwen3vl.py photo.jpg photo.bin --size 448x448 + + # 从 ONNX 模型自动读取输入尺寸 + python preprocess_qwen3vl.py photo.jpg photo.bin --onnx-model vision.onnx + + # 自动检测 ONNX 内置归一化并选择处理方式(默认) + python preprocess_qwen3vl.py photo.jpg photo.bin --onnx-model vision.onnx --norm-mode auto + + # 强制输出 0..255 float32(适用于 ONNX 已内置归一化) + python preprocess_qwen3vl.py photo.jpg photo.bin --onnx-model vision.onnx --norm-mode none + + # 自定义 token 范围 + python preprocess_qwen3vl.py photo.jpg photo.bin --min-tokens 256 --max-tokens 1280 + + # 自定义归一化参数 + python preprocess_qwen3vl.py photo.jpg photo.bin --mean 0.5,0.5,0.5 --std 0.5,0.5,0.5 + """) + + parser.add_argument("input", help="输入图像路径 (jpg/png 等)") + parser.add_argument("output", help="输出 .bin 文件路径") + + size_group = parser.add_argument_group("尺寸控制 (三选一)") + size_group.add_argument("--size", type=str, default=None, + help="固定输出尺寸, 格式: WxH (如 448x448)") + size_group.add_argument("--onnx-model", type=str, default=None, + help="ONNX 视觉模型路径, 自动从模型读取输入尺寸") + + token_group = parser.add_argument_group("Smart Resize 参数 (当未指定 --size 或 --onnx-model 时生效)") + token_group.add_argument("--patch-size", type=int, default=DEFAULT_PATCH_SIZE, + help=f"patch 大小 (默认: {DEFAULT_PATCH_SIZE})") + token_group.add_argument("--merge-size", type=int, default=DEFAULT_MERGE_SIZE, + help=f"merge 大小 (默认: {DEFAULT_MERGE_SIZE})") + token_group.add_argument("--min-tokens", type=int, default=DEFAULT_MIN_TOKENS, + help=f"最小图像 token 数 (默认: {DEFAULT_MIN_TOKENS})") + token_group.add_argument("--max-tokens", type=int, default=DEFAULT_MAX_TOKENS, + help=f"最大图像 token 数 (默认: {DEFAULT_MAX_TOKENS})") + + norm_group = parser.add_argument_group("归一化参数") + norm_group.add_argument("--norm-mode", choices=["auto", "external", "none"], default="auto", + help="归一化模式: auto(自动), external(外部归一化), none(不做外部归一化,输出0..255)") + norm_group.add_argument("--mean", type=str, default=None, + help="RGB 均值, 逗号分隔 (默认: 0.48145466,0.4578275,0.40821073)") + norm_group.add_argument("--std", type=str, default=None, + help="RGB 标准差, 逗号分隔 (默认: 0.26862954,0.26130258,0.27577711)") + + args = parser.parse_args() + + # 解析尺寸 + target_h, target_w = None, None + if args.size: + target_h, target_w = parse_size(args.size) + + # 解析归一化参数 + image_mean = [float(x) for x in args.mean.split(",")] if args.mean else None + image_std = [float(x) for x in args.std.split(",")] if args.std else None + + preprocess( + image_path=args.input, + output_path=args.output, + target_h=target_h, + target_w=target_w, + patch_size=args.patch_size, + merge_size=args.merge_size, + min_tokens=args.min_tokens, + max_tokens=args.max_tokens, + image_mean=image_mean, + image_std=image_std, + onnx_model=args.onnx_model, + norm_mode=args.norm_mode, + ) + + +if __name__ == "__main__": + main() From d8c0e6523fbcbd6b56bdb7b3bb02e523bacbde97 Mon Sep 17 00:00:00 2001 From: cailinxi Date: Fri, 6 Mar 2026 06:26:07 +0000 Subject: [PATCH 06/40] ep vision: add direct jpg preprocessing for server and mtmd cli Change-Id: Iace35d9a7e8df6e213c8ef127010dd6884454afc --- docs/multimodal/llama-mtmd-cli-ep.md | 18 +- tools/mtmd/CMakeLists.txt | 3 + tools/mtmd/ep-vision-preprocess.cpp | 245 +++++++++++++++++++++++++++ tools/mtmd/ep-vision-preprocess.h | 19 +++ tools/mtmd/mtmd-cli-ep.cpp | 98 ++++++++++- tools/server/server-common.cpp | 25 ++- tools/server/server-common.h | 2 + tools/server/server-ep-vision.cpp | 15 +- 8 files changed, 407 insertions(+), 18 deletions(-) create mode 100644 tools/mtmd/ep-vision-preprocess.cpp create mode 100644 tools/mtmd/ep-vision-preprocess.h diff --git a/docs/multimodal/llama-mtmd-cli-ep.md b/docs/multimodal/llama-mtmd-cli-ep.md index 783dd6e7d1c2..0af9b9f08555 100644 --- a/docs/multimodal/llama-mtmd-cli-ep.md +++ b/docs/multimodal/llama-mtmd-cli-ep.md @@ -3,7 +3,7 @@ `llama-mtmd-cli-ep` 是基于 `llama.cpp` 的多模态命令行推理工具,专为 Spacemit EP ONNX 视觉引擎设计。 - **文本推理**:由 llama.cpp 加载 GGUF 格式的文本模型完成 -- **视觉编码**:由 Spacemit EP ONNX 引擎完成,读取预处理的图像二进制文件(`.bin`) +- **视觉编码**:由 Spacemit EP ONNX 引擎完成,支持直接输入 `jpg/png`(内部预处理)或预处理的 `.bin` - **运行模式**:支持单轮推理和交互聊天两种模式 > **状态说明(重要)**: @@ -31,7 +31,7 @@ | 对比项 | 原生 `llama-mtmd-cli` | EP 版 `llama-mtmd-cli-ep` | |--------|----------------------|--------------------------| | `--mmproj` 指向 | `mmproj.gguf` 文件 | EP 配置目录(含 `config.json` + ONNX 模型) | -| `--image` 格式 | jpg / png 等常见图片格式 | 预处理后的二进制文件(`.bin`) | +| `--image` 格式 | jpg / png 等常见图片格式 | `jpg/png`(内部预处理)或预处理后的二进制文件(`.bin`) | | 视觉编码后端 | CLIP/GGUF | Spacemit EP ONNX 引擎 | | 音频支持 | 支持 | 不支持(仅视觉) | @@ -48,9 +48,9 @@ - `config.json`:视觉模型配置,其中的 `hidden_size` **必须**与文本模型的 `n_embd` 一致 - 视觉 ONNX 模型文件(如 `fastvlm_vision.f16.onnx`、`qwen3_vl_vision.q_replaceneg.onnx`) -3. **预处理后的图像二进制文件** - - 例如 `input.bin`、`input2.bin` - - 这些文件由外部预处理工具生成,不是原始的 jpg/png +3. **图像输入** + - 支持直接传入原始图像文件(如 `input.jpg`、`input.png`) + - 也支持传入预处理后的二进制文件(如 `input.bin`、`input2.bin`) > **注意**:如果 `config.json` 中的 `hidden_size` 与文本模型的 `n_embd` 不一致,程序会报错并退出。 @@ -69,7 +69,7 @@ | 参数 | 格式 | 说明 | |------|------|------| -| `--image` | `--image ` | 预处理的图像二进制文件路径。支持两种方式指定多个图像:① 逗号分隔 `--image a.bin,b.bin`;② 重复参数 `--image a.bin --image b.bin`。当与 `-p` 同时提供时进入**单轮推理模式**。 | +| `--image` | `--image ` | 图像路径,支持 `jpg/png`(内部预处理)和预处理 `.bin`。支持两种方式指定多个图像:① 逗号分隔 `--image a.jpg,b.jpg`;② 重复参数 `--image a.jpg --image b.jpg`。当与 `-p` 同时提供时进入**单轮推理模式**。 | | `-p` | `-p "<提示词>"` | 用户提示词。在提示词中使用 `<__media__>` 标记图像插入位置。当与 `--image` 同时提供时进入**单轮推理模式**。 | > 当 `--image` 和 `-p` **同时提供**时为单轮推理模式;否则进入交互聊天模式。 @@ -206,7 +206,7 @@ llama-mtmd-cli-ep \ ``` Running in chat mode (EP vision), available commands: - /image load a preprocessed image binary + /image load an image (.jpg/.png/...) or preprocessed .bin /clear clear the chat history /quit or /exit exit the program ``` @@ -215,7 +215,7 @@ Running in chat mode (EP vision), available commands: | 命令 | 说明 | |------|------| -| `/image ` | 加载一个预处理的图像二进制文件,并在当前输入中追加一个 `<__media__>` 标记。可以在发送文本前多次使用来加载多张图片。 | +| `/image ` | 加载一个图像文件(`jpg/png/...`)或预处理 `.bin`,并在当前输入中追加一个 `<__media__>` 标记。可以在发送文本前多次使用来加载多张图片。 | | `/clear` | 清空聊天历史和上下文,恢复到初始状态。如有系统提示词会重新评估。 | | `/quit` 或 `/exit` | 退出程序。 | | `Ctrl+C` | 中断当前生成。再按一次 `Ctrl+C` 退出程序。 | @@ -426,7 +426,7 @@ llama-mtmd-cli-ep \ ## 10. 当前限制 - 仅支持视觉输入(图像),**不支持音频输入** -- 图像输入必须是预处理后的二进制文件(`.bin`),不能直接使用 jpg/png +- 对于当前已验证链路,`fastvlm` 与 `qwen3vl` 支持直接输入 `jpg/png`(内部预处理)和 `.bin` - 端到端仅在 FastVLM、Qwen3VL 上实测通过;其它模型请视为“未验证状态” - 建议使用默认的环境变量配置以保持稳定: - `MTMD_EP_IMAGE_BOUNDARY=native` diff --git a/tools/mtmd/CMakeLists.txt b/tools/mtmd/CMakeLists.txt index 97be4b416ec1..c467f5713ae3 100644 --- a/tools/mtmd/CMakeLists.txt +++ b/tools/mtmd/CMakeLists.txt @@ -6,6 +6,8 @@ add_library(mtmd mtmd.cpp mtmd-audio.cpp mtmd-image.cpp + ep-vision-preprocess.cpp + ep-vision-preprocess.h mtmd.h mtmd-helper.cpp mtmd-helper.h @@ -163,6 +165,7 @@ if(MTMD_BUILD_EP_CLI) target_link_libraries(${EP_TARGET} PRIVATE llama-common + mtmd llama ggml onnxruntime diff --git a/tools/mtmd/ep-vision-preprocess.cpp b/tools/mtmd/ep-vision-preprocess.cpp new file mode 100644 index 000000000000..3926ba9a1192 --- /dev/null +++ b/tools/mtmd/ep-vision-preprocess.cpp @@ -0,0 +1,245 @@ +#include "ep-vision-preprocess.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "stb/stb_image.h" + +namespace { + +static std::string to_lower_ascii(std::string s) { + std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { + return (char) std::tolower(c); + }); + return s; +} + +static bool contains_icase(const std::string & text, const std::string & pattern) { + return to_lower_ascii(text).find(to_lower_ascii(pattern)) != std::string::npos; +} + +struct ep_preproc_spec { + int32_t target_w = 0; + int32_t target_h = 0; + bool normalize_to_01 = false; + bool quantize_to_u8_after_resize = false; +}; + +static ep_preproc_spec resolve_preproc_spec(const std::string & architecture) { + // Qwen3VL EP ONNX keeps internal (x - 127.5) / 127.5 preprocessing. + if (contains_icase(architecture, "qwen3vl")) { + return {/* target_w */ 768, /* target_h */ 768, /* normalize_to_01 */ false, /* quantize */ true}; + } + + // FastVLM (LlavaQwen2ForCausalLM) expects 0..1 normalized CHW float32. + if (contains_icase(architecture, "llavaqwen2forcausallm") || + contains_icase(architecture, "llavaqwen2") || + contains_icase(architecture, "fastvlm")) { + return {/* target_w */ 512, /* target_h */ 512, /* normalize_to_01 */ true, /* quantize */ true}; + } + + return {}; +} + +struct linear_contrib { + std::vector idx; + std::vector w; +}; + +static std::vector precompute_linear_contrib(int32_t in_size, int32_t out_size) { + if (in_size <= 0 || out_size <= 0) { + throw std::runtime_error("Invalid resize dimensions"); + } + + const float scale = (float) in_size / (float) out_size; + const float scale_factor = scale > 1.0f ? scale : 1.0f; + const float support = scale > 1.0f ? scale : 1.0f; + + std::vector table((size_t) out_size); + for (int32_t o = 0; o < out_size; ++o) { + const float center = ((float) o + 0.5f) * scale - 0.5f; + const int32_t left = (int32_t) std::ceil(center - support); + const int32_t right = (int32_t) std::floor(center + support); + + auto & c = table[(size_t) o]; + c.idx.reserve((size_t) std::max(0, right - left + 1)); + c.w.reserve((size_t) std::max(0, right - left + 1)); + + float w_sum = 0.0f; + for (int32_t i = left; i <= right; ++i) { + const float x = ((float) i - center) / scale_factor; + const float w = std::max(0.0f, 1.0f - std::fabs(x)); + c.idx.push_back(std::clamp(i, 0, in_size - 1)); + c.w.push_back(w); + w_sum += w; + } + + if (w_sum > 0.0f) { + for (auto & w : c.w) { + w /= w_sum; + } + } + } + + return table; +} + +static std::vector resize_rgb_u8_antialias( + const uint8_t * src, + int32_t src_w, + int32_t src_h, + int32_t dst_w, + int32_t dst_h, + bool quantize_u8) { + if (src == nullptr || src_w <= 0 || src_h <= 0 || dst_w <= 0 || dst_h <= 0) { + throw std::runtime_error("Invalid image dimensions"); + } + + const auto contrib_x = precompute_linear_contrib(src_w, dst_w); + const auto contrib_y = precompute_linear_contrib(src_h, dst_h); + + std::vector tmp((size_t) src_h * (size_t) dst_w * 3, 0.0f); + for (int32_t y = 0; y < src_h; ++y) { + for (int32_t x = 0; x < dst_w; ++x) { + const auto & c = contrib_x[(size_t) x]; + for (size_t k = 0; k < c.idx.size(); ++k) { + const int32_t sx = c.idx[k]; + const float w = c.w[k]; + const size_t s_idx = ((size_t) y * (size_t) src_w + (size_t) sx) * 3; + const size_t d_idx = ((size_t) y * (size_t) dst_w + (size_t) x) * 3; + tmp[d_idx + 0] += (float) src[s_idx + 0] * w; + tmp[d_idx + 1] += (float) src[s_idx + 1] * w; + tmp[d_idx + 2] += (float) src[s_idx + 2] * w; + } + } + } + + std::vector out((size_t) dst_h * (size_t) dst_w * 3, 0); + for (int32_t y = 0; y < dst_h; ++y) { + const auto & c = contrib_y[(size_t) y]; + for (int32_t x = 0; x < dst_w; ++x) { + float acc[3] = {0.0f, 0.0f, 0.0f}; + for (size_t k = 0; k < c.idx.size(); ++k) { + const int32_t sy = c.idx[k]; + const float w = c.w[k]; + const size_t s_idx = ((size_t) sy * (size_t) dst_w + (size_t) x) * 3; + acc[0] += tmp[s_idx + 0] * w; + acc[1] += tmp[s_idx + 1] * w; + acc[2] += tmp[s_idx + 2] * w; + } + + const size_t d_idx = ((size_t) y * (size_t) dst_w + (size_t) x) * 3; + for (int c_id = 0; c_id < 3; ++c_id) { + float v = quantize_u8 ? std::round(acc[c_id]) : acc[c_id]; + v = std::clamp(v, 0.0f, 255.0f); + out[d_idx + (size_t) c_id] = (uint8_t) v; + } + } + } + + return out; +} + +static std::vector rgb_u8_to_chw_f32( + const std::vector & src, + int32_t w, + int32_t h, + bool normalize_to_01) { + const size_t plane = (size_t) w * (size_t) h; + if (src.size() != plane * 3) { + throw std::runtime_error("Invalid RGB tensor size"); + } + + std::vector out(plane * 3, 0.0f); + for (int32_t y = 0; y < h; ++y) { + for (int32_t x = 0; x < w; ++x) { + const size_t src_idx = ((size_t) y * (size_t) w + (size_t) x) * 3; + const size_t dst_idx = (size_t) y * (size_t) w + (size_t) x; + for (int32_t c = 0; c < 3; ++c) { + float v = (float) src[src_idx + (size_t) c]; + if (normalize_to_01) { + v /= 255.0f; + } + out[(size_t) c * plane + dst_idx] = v; + } + } + } + return out; +} + +static std::vector pack_f32_bytes(const std::vector & values) { + if (values.empty()) { + return {}; + } + + if (values.size() > std::numeric_limits::max() / sizeof(float)) { + throw std::runtime_error("float tensor is too large"); + } + + std::vector out(values.size() * sizeof(float), 0); + std::memcpy(out.data(), values.data(), out.size()); + return out; +} + +} // namespace + +ep_vision_preprocess_result ep_vision_preprocess_if_image( + const std::vector & input, + const std::string & architecture) { + ep_vision_preprocess_result out; + if (input.empty()) { + return out; + } + + if (input.size() > (size_t) std::numeric_limits::max()) { + return out; + } + + int src_w = 0, src_h = 0, src_c = 0; + uint8_t * pixels = stbi_load_from_memory( + input.data(), + (int) input.size(), + &src_w, &src_h, &src_c, + /* desired_channels */ 3); + if (pixels == nullptr) { + return out; + } + + try { + const ep_preproc_spec spec = resolve_preproc_spec(architecture); + if (spec.target_w <= 0 || spec.target_h <= 0) { + stbi_image_free(pixels); + throw std::runtime_error( + "EP image preprocessing for architecture '" + architecture + + "' is not configured yet; please provide preprocessed .bin"); + } + + const auto resized_u8 = resize_rgb_u8_antialias( + pixels, + src_w, src_h, + spec.target_w, spec.target_h, + spec.quantize_to_u8_after_resize); + const auto f32 = rgb_u8_to_chw_f32( + resized_u8, + spec.target_w, spec.target_h, + spec.normalize_to_01); + stbi_image_free(pixels); + + out.was_image = true; + out.target_w = spec.target_w; + out.target_h = spec.target_h; + out.normalize_to_01 = spec.normalize_to_01; + out.tensor_bytes = pack_f32_bytes(f32); + return out; + + } catch (...) { + stbi_image_free(pixels); + throw; + } +} diff --git a/tools/mtmd/ep-vision-preprocess.h b/tools/mtmd/ep-vision-preprocess.h new file mode 100644 index 000000000000..e41180fc6f8a --- /dev/null +++ b/tools/mtmd/ep-vision-preprocess.h @@ -0,0 +1,19 @@ +#pragma once + +#include +#include +#include + +struct ep_vision_preprocess_result { + bool was_image = false; + int32_t target_w = 0; + int32_t target_h = 0; + bool normalize_to_01 = false; + std::vector tensor_bytes; +}; + +// If input bytes decode as image (jpg/png/webp/...), preprocess them into +// float32 NCHW bytes for EP vision ONNX input. Otherwise returns was_image=false. +ep_vision_preprocess_result ep_vision_preprocess_if_image( + const std::vector & input, + const std::string & architecture); diff --git a/tools/mtmd/mtmd-cli-ep.cpp b/tools/mtmd/mtmd-cli-ep.cpp index b3dee3952eaf..d6421c312b0c 100644 --- a/tools/mtmd/mtmd-cli-ep.cpp +++ b/tools/mtmd/mtmd-cli-ep.cpp @@ -11,6 +11,7 @@ #include "console.h" #include "chat.h" #include "ep-vision-wrapper.h" +#include "ep-vision-preprocess.h" #include #include @@ -19,6 +20,9 @@ #include #include #include +#include +#include +#include #include #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) @@ -39,7 +43,7 @@ static volatile bool g_is_interrupted = false; static void show_additional_info(int /*argc*/, char ** argv) { LOG( "Multimodal CLI with Spacemit EP vision engine\n\n" - "Usage: %s [options] -m --mmproj --image -p \n\n" + "Usage: %s [options] -m --mmproj --image -p \n\n" " -m and --mmproj are required (or set EP_CONFIG_DIR)\n" " --image and -p are optional, if NOT provided, the CLI will run in chat mode\n", argv[0] @@ -388,6 +392,60 @@ static std::vector split_keep_marker(const std::string & input, con return out; } +static std::vector read_binary_file(const std::string & path) { + std::ifstream file(path, std::ios::binary); + if (!file) { + throw std::runtime_error("Unable to open image file: " + path); + } + + return std::vector((std::istreambuf_iterator(file)), std::istreambuf_iterator()); +} + +static std::string write_temp_bin_file(const std::vector & data) { +#if defined(_WIN32) + char temp_path[MAX_PATH] = {0}; + char temp_file[MAX_PATH] = {0}; + + if (GetTempPathA(MAX_PATH, temp_path) == 0) { + throw std::runtime_error("failed to get temp path"); + } + if (GetTempFileNameA(temp_path, "mep", 0, temp_file) == 0) { + throw std::runtime_error("failed to create temp file"); + } + + FILE * fp = std::fopen(temp_file, "wb"); + if (!fp) { + throw std::runtime_error("failed to open temp file"); + } + const size_t n = std::fwrite(data.data(), 1, data.size(), fp); + std::fclose(fp); + if (n != data.size()) { + std::remove(temp_file); + throw std::runtime_error("failed to write temp file"); + } + return std::string(temp_file); +#else + char tmpl[] = "/tmp/llama-mtmd-ep-XXXXXX"; + const int fd = mkstemp(tmpl); + if (fd < 0) { + throw std::runtime_error("failed to create temp file"); + } + + size_t written = 0; + while (written < data.size()) { + const ssize_t n = write(fd, data.data() + written, data.size() - written); + if (n <= 0) { + close(fd); + std::remove(tmpl); + throw std::runtime_error("failed to write temp file"); + } + written += (size_t) n; + } + close(fd); + return std::string(tmpl); +#endif +} + static void append_text_chunk(std::vector & chunks, std::vector && tokens) { if (tokens.empty()) { return; @@ -844,7 +902,39 @@ static int eval_message_ep(mtmd_cli_ep_context & ctx, common_chat_msg & msg) { // image chunk LOG_INF("Encoding image chunk %zu with EP vision engine: %s\n", i, chunk.image_path.c_str()); - std::vector image_embd = ctx.ep_ctx->encode_image(chunk.image_path); + std::string ep_input_path = chunk.image_path; + std::string temp_input_path; + try { + const auto image_bytes = read_binary_file(chunk.image_path); + auto preproc = ep_vision_preprocess_if_image(image_bytes, ctx.ep_ctx->architecture()); + if (preproc.was_image) { + temp_input_path = write_temp_bin_file(preproc.tensor_bytes); + ep_input_path = temp_input_path; + LOG_INF("[EP-v3] preprocessed image '%s' -> [1,3,%d,%d] float32 (%s)\n", + chunk.image_path.c_str(), + preproc.target_h, + preproc.target_w, + preproc.normalize_to_01 ? "0..1" : "0..255"); + } + } catch (const std::exception & e) { + LOG_ERR("Failed to prepare image '%s': %s\n", chunk.image_path.c_str(), e.what()); + return 1; + } + + std::vector image_embd; + try { + image_embd = ctx.ep_ctx->encode_image(ep_input_path); + if (!temp_input_path.empty()) { + std::remove(temp_input_path.c_str()); + } + } catch (const std::exception & e) { + if (!temp_input_path.empty()) { + std::remove(temp_input_path.c_str()); + } + LOG_ERR("Failed to encode image chunk %zu (%s): %s\n", i, chunk.image_path.c_str(), e.what()); + return 1; + } + if (image_embd.empty() || image_embd.size() % (size_t)ctx.hidden_size != 0) { LOG_ERR("Invalid image embedding shape from EP (size=%zu, hidden_size=%" PRId64 ")\n", image_embd.size(), ctx.hidden_size); @@ -989,7 +1079,7 @@ int main(int argc, char ** argv) { } else { // Chat mode LOG("\n Running in chat mode (EP vision), available commands:"); - LOG("\n /image load a preprocessed image binary"); + LOG("\n /image load an image (.jpg/.png/...) or preprocessed .bin"); LOG("\n /clear clear the chat history"); LOG("\n /quit or /exit exit the program"); LOG("\n"); @@ -1031,7 +1121,7 @@ int main(int argc, char ** argv) { } std::string media_path = line.substr(7); ctx.add_image(media_path); - LOG("%s image binary loaded\n", media_path.c_str()); + LOG("%s image loaded\n", media_path.c_str()); content += "<__media__>"; continue; } else { diff --git a/tools/server/server-common.cpp b/tools/server/server-common.cpp index aec2ab1d2f1e..f560bd4af84b 100644 --- a/tools/server/server-common.cpp +++ b/tools/server/server-common.cpp @@ -12,6 +12,8 @@ #include #include #include +#include +#include json format_error_response(const std::string & message, const enum error_type type) { std::string type_str; @@ -1074,6 +1076,19 @@ static void handle_media( json & media_obj, const std::string & media_path, bool image_bin_only) { + auto is_ep_supported_image_file = [](const std::string & path) { + std::string lower = path; + std::transform(lower.begin(), lower.end(), lower.begin(), [](unsigned char c) { + return (char) std::tolower(c); + }); + return string_ends_with(lower, ".jpg") || + string_ends_with(lower, ".jpeg") || + string_ends_with(lower, ".png") || + string_ends_with(lower, ".webp") || + string_ends_with(lower, ".bmp") || + string_ends_with(lower, ".gif"); + }; + std::string url = json_value(media_obj, "url", std::string()); if (string_starts_with(url, "http")) { // download remote image @@ -1098,8 +1113,8 @@ static void handle_media( } // load local image file std::string file_path = url.substr(7); // remove "file://" - if (image_bin_only && !string_ends_with(file_path, ".bin")) { - throw std::invalid_argument("EP backend expects .bin file for file:// image_url"); + if (image_bin_only && !string_ends_with(file_path, ".bin") && !is_ep_supported_image_file(file_path)) { + throw std::invalid_argument("EP backend expects file:// image_url to be .bin or image file (.jpg/.jpeg/.png/.webp/.bmp/.gif)"); } raw_buffer data; if (!fs_validate_filename(file_path, true)) { @@ -1118,8 +1133,10 @@ static void handle_media( std::vector parts = string_split(url, /*separator*/ ','); if (parts.size() != 2) { throw std::runtime_error("Invalid url value"); - } else if (image_bin_only && !string_starts_with(parts[0], "data:application/octet-stream")) { - throw std::runtime_error("EP backend expects data:application/octet-stream;base64"); + } else if (image_bin_only && + !string_starts_with(parts[0], "data:application/octet-stream") && + !string_starts_with(parts[0], "data:image/")) { + throw std::runtime_error("EP backend expects data:application/octet-stream;base64 or data:image/*;base64"); } else if (!image_bin_only && !string_starts_with(parts[0], "data:image/")) { throw std::runtime_error("Invalid url format: " + parts[0]); } else if (!string_ends_with(parts[0], "base64")) { diff --git a/tools/server/server-common.h b/tools/server/server-common.h index d67c6f1b472d..585406476a94 100644 --- a/tools/server/server-common.h +++ b/tools/server/server-common.h @@ -311,6 +311,8 @@ struct server_chat_params { common_chat_templates_ptr tmpls; bool allow_image; bool allow_audio; + // Legacy flag name: when true, parsing follows EP vision media rules + // (.bin tensors and raw image payloads handled by EP preprocessing path). bool image_bin_only = false; std::string vision_backend = "none"; bool enable_thinking = true; diff --git a/tools/server/server-ep-vision.cpp b/tools/server/server-ep-vision.cpp index 287cfa84e6a1..2434b0220bab 100644 --- a/tools/server/server-ep-vision.cpp +++ b/tools/server/server-ep-vision.cpp @@ -17,6 +17,7 @@ #if defined(LLAMA_SERVER_EP_VISION) #include "../mtmd/ep-vision-wrapper.h" +#include "../mtmd/ep-vision-preprocess.h" #endif #if defined(_WIN32) @@ -432,7 +433,19 @@ server_ep_image_chunk server_ep_vision_encode_image_bin( #if defined(LLAMA_SERVER_EP_VISION) std::lock_guard lock(ctx->mu); - const std::string tmp_file = write_temp_bin_file(data); + + std::vector ep_input = data; + auto preproc = ep_vision_preprocess_if_image(data, ctx->architecture); + if (preproc.was_image) { + ep_input = std::move(preproc.tensor_bytes); + LOG_INF("[server-ep] preprocessed image for arch=%s -> [1,3,%d,%d] float32 (%s)\n", + ctx->architecture.c_str(), + preproc.target_h, + preproc.target_w, + preproc.normalize_to_01 ? "0..1" : "0..255"); + } + + const std::string tmp_file = write_temp_bin_file(ep_input); server_ep_image_chunk out; try { From b2d780f4220b91c24af908603defad7b52f152d1 Mon Sep 17 00:00:00 2001 From: cailinxi Date: Fri, 6 Mar 2026 06:40:42 +0000 Subject: [PATCH 07/40] docs: add EP multimodal usage and qwen3vl tuning note Change-Id: I19f539c9bc986165a0af2e00b90481c093a7db26 --- docs/multimodal.md | 46 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/docs/multimodal.md b/docs/multimodal.md index 33d1df33c3bb..c1ef6ee62d8c 100644 --- a/docs/multimodal.md +++ b/docs/multimodal.md @@ -1,7 +1,8 @@ # Multimodal -llama.cpp supports multimodal input via `libmtmd`. Currently, there are 2 tools support this feature: +llama.cpp supports multimodal input via `libmtmd`. Currently, there are 3 tools support this feature: - [llama-mtmd-cli](../tools/mtmd/README.md) +- [llama-mtmd-cli-ep](./multimodal/llama-mtmd-cli-ep.md) (Spacemit EP ONNX vision backend) - [llama-server](../tools/server/README.md) via OpenAI-compatible `/chat/completions` API Currently, we support **image** and **audio** input. Audio is highly experimental and may have reduced quality. @@ -40,6 +41,49 @@ llama-server -hf ggml-org/gemma-3-4b-it-GGUF --no-mmproj-offload > - Dots.OCR: https://github.com/ggml-org/llama.cpp/pull/17575 > - HunyuanOCR: https://github.com/ggml-org/llama.cpp/pull/21395 +## Spacemit EP vision backend + +The EP vision backend is an alternative multimodal path for supported deployments (for example FastVLM and Qwen3VL with Spacemit EP ONNX vision models). + +- For detailed `llama-mtmd-cli-ep` behavior and options, see: [llama-mtmd-cli-ep.md](./multimodal/llama-mtmd-cli-ep.md) +- For server options, see `llama-server --help` (`--vision-backend ep`, `--ep-config-dir

`) + +### `llama-mtmd-cli-ep` example + +```sh +llama-mtmd-cli-ep \ + -m /path/to/qwen3vl-30b-text-q4_1.gguf \ + --mmproj /path/to/ep_config_dir \ + --image /path/to/input.jpg \ + -p "<__media__>Describe this image." \ + -c 1024 -b 128 -ctk q4_0 -ctv q8_0 +``` + +### `llama-server` EP example + +```sh +llama-server \ + -m /path/to/qwen3vl-30b-text-q4_1.gguf \ + --vision-backend ep \ + --ep-config-dir /path/to/ep_config_dir \ + --media-path /path/to/media_root/ \ + -c 1024 -b 128 -ctk q4_0 -ctv q8_0 +``` + +With EP backend, image input can be sent as regular image files (`.jpg`, `.png`, etc.) or preprocessed `.bin` tensors. + +### Qwen3VL-30B practical note + +`qwen3vl-30b` is very large. In practice, you should constrain context length and KV cache quantization. + +One known workable configuration is: + +```sh +-c 1024 -b 128 -ctk q4_0 -ctv q8_0 +``` + +Other configurations are possible and should be tuned per hardware and workload. + ## Pre-quantized models These are ready-to-use models, most of them come with `Q4_K_M` quantization by default. They can be found at the Hugging Face page of the ggml-org: https://huggingface.co/collections/ggml-org/multimodal-ggufs-68244e01ff1f39e5bebeeedc From b3a0b253439c9b49adb463cc61355e01c7e819cc Mon Sep 17 00:00:00 2001 From: cailinxi Date: Tue, 10 Mar 2026 02:43:46 +0000 Subject: [PATCH 08/40] update doc Change-Id: Iae70b7f51270d1197eba44130c7b39f11ea1a8b4 --- docs/multimodal.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/multimodal.md b/docs/multimodal.md index c1ef6ee62d8c..b85ca10aa421 100644 --- a/docs/multimodal.md +++ b/docs/multimodal.md @@ -67,7 +67,7 @@ llama-server \ --vision-backend ep \ --ep-config-dir /path/to/ep_config_dir \ --media-path /path/to/media_root/ \ - -c 1024 -b 128 -ctk q4_0 -ctv q8_0 + -c 1024 -b 128 -ctk q4_0 -ctv q8_0 --host 0.0.0.0 --port 8080 ``` With EP backend, image input can be sent as regular image files (`.jpg`, `.png`, etc.) or preprocessed `.bin` tensors. From 46e213e2d7b903e709252d3276eee9a1e8ce62e8 Mon Sep 17 00:00:00 2001 From: cailinxi Date: Tue, 10 Mar 2026 03:25:46 +0000 Subject: [PATCH 09/40] updating build doc for EP accelerator Change-Id: I13e7fa811f023d908229033444abb9f94276c810 --- docs/build-riscv64-spacemit.md | 77 +++++++++++++++++++++++++++++++++- 1 file changed, 76 insertions(+), 1 deletion(-) diff --git a/docs/build-riscv64-spacemit.md b/docs/build-riscv64-spacemit.md index 08301d51caeb..b44742758fe9 100644 --- a/docs/build-riscv64-spacemit.md +++ b/docs/build-riscv64-spacemit.md @@ -95,7 +95,6 @@ marchid : 0x8000000041000002 mimpid : 0x10000000d5686200 hart isa : rv64imafdcv_zicbom_zicbop_zicboz_zicntr_zicond_zicsr_zifencei_zihintntl_zihintpause_zihpm_zimop_zaamo_zalrsc_zawrs_zfa_zfh_zfhmin_zca_zcb_zcd_zcmop_zba_zbb_zbc_zbs_zkt_zvbb_zvbc_zve32f_zve32x_zve64d_zve64f_zve64x_zvfh_zvfhmin_zvkb_zvkg_zvkned_zvknha_zvknhb_zvksed_zvksh_zvkt_smaia_smstateen_ssaia_sscofpmf_sstc_svinval_svnapot_svpbmt_sdtrig ~~~ - | model | size | params | backend | threads | n_ubatch | fa | mmap | test | t/s | | ------------------------------ | ---------: | ---------: | ---------- | ------: | -------: | -: | ---: | --------------: | -------------------: | | qwen3 0.6B Q4_0 | 358.78 MiB | 596.05 M | CPU | 8 | 128 | 1 | 0 | pp128 | 565.83 ± 0.31 | @@ -108,3 +107,79 @@ hart isa : rv64imafdcv_zicbom_zicbop_zicboz_zicntr_zicond_zicsr_zifencei_ | qwen35 2B Q4_1 | 1.19 GiB | 1.88 B | CPU | 8 | 128 | 1 | 0 | tg128 | 16.49 ± 0.01 | | gemma4 E4B Q4_K - Medium | 4.76 GiB | 7.52 B | CPU | 8 | 128 | 1 | 0 | pp128 | 21.13 ± 0.01 | | gemma4 E4B Q4_K - Medium | 4.76 GiB | 7.52 B | CPU | 8 | 128 | 1 | 0 | tg128 | 5.66 ± 0.00 | + +## Build and run with EP acceleration + +To enable the Spacemit EP vision backend in addition to the default CPU build, the build must also include the EP-related CMake options and point to both the `spacemit-ep` source tree and the `onnxruntime` build tree. + +### Build + +The EP-enabled build needs these additional CMake definitions: + +- `-DMTMD_BUILD_EP_CLI=ON` +- `-DLLAMA_SERVER_EP_VISION=ON` +- `-DSPACEMIT_EP_DIR=` +- `-DONNXRUNTIME_INC_DIR=/include/onnxruntime` +- `-DONNXRUNTIME_LIB_DIR=/build/Linux/rv64/Release` + +Example full build command: + +```bash +export SPACEMIT_EP_DIR=/path/to/spacemit-ep +export ONNXRUNTIME_DIR=/path/to/onnxruntime +export LD_LIBRARY_PATH=${ONNXRUNTIME_DIR}/build/Linux/rv64/Release:${LD_LIBRARY_PATH} + +cmake -B build \ + -DCMAKE_BUILD_TYPE=Release \ + -DGGML_CPU_RISCV64_SPACEMIT=ON \ + -DGGML_CPU_REPACK=ON \ + -DLLAMA_OPENSSL=OFF \ + -DGGML_RVV=ON \ + -DGGML_RV_ZVFH=ON \ + -DGGML_RV_ZFH=ON \ + -DGGML_RV_ZICBOP=ON \ + -DGGML_RV_ZIHINTPAUSE=ON \ + -DGGML_RV_ZBA=ON \ + -DCMAKE_TOOLCHAIN_FILE=${PWD}/cmake/riscv64-spacemit-linux-gnu-gcc.cmake \ + -DCMAKE_INSTALL_PREFIX=build/installed \ + -DMTMD_BUILD_EP_CLI=ON \ + -DLLAMA_SERVER_EP_VISION=ON \ + -DSPACEMIT_EP_DIR=${SPACEMIT_EP_DIR} \ + -DONNXRUNTIME_INC_DIR=${ONNXRUNTIME_DIR}/include/onnxruntime \ + -DONNXRUNTIME_LIB_DIR=${ONNXRUNTIME_DIR}/build/Linux/rv64/Release + +cmake --build build --parallel $(nproc) --config Release + +pushd build +make install +popd +``` + +### Run + +At runtime, EP-enabled binaries need to find both ONNX Runtime and the Spacemit EP provider shared library. Make sure `LD_LIBRARY_PATH` includes: + +- the ONNX Runtime library directory +- the Spacemit EP library directory +- the installed llama.cpp library directory if running from an installed package + +Example: + +```bash +export LD_LIBRARY_PATH=/path/to/onnxruntime/build/Linux/rv64/Release:/path/to/spacemit-ep/build/rv64/Release/installed/lib:./build/installed/lib:${LD_LIBRARY_PATH} +``` + +For `llama-server`, also pass the EP config directory at runtime, for example: + +```bash +./build/bin/llama-server \ + -m /path/to/model.gguf \ + --vision-backend ep \ + --ep-config-dir /path/to/ep-config-dir +``` + +Notes: + +- `--ep-config-dir` should point to the directory containing `config.json` and the EP vision ONNX model files. +- If `libspacemit_ep.so` is missing from `LD_LIBRARY_PATH`, EP session initialization will fail at runtime. +- If `libonnxruntime.so` is missing from `LD_LIBRARY_PATH`, the EP-enabled binary will not run successfully. From 9a3f28d5abb7474944a2c156ade1d6bda2cc8255 Mon Sep 17 00:00:00 2001 From: cailinxi Date: Wed, 11 Mar 2026 11:56:41 +0000 Subject: [PATCH 10/40] smt: simplify spacemit vision integration Change-Id: I465daed1cfa7912c61cf1137431bf9e0e4247c56 --- CMakeLists.txt | 5 + common/arg.cpp | 18 +- common/common.h | 4 +- docs/build-riscv64-spacemit.md | 148 +++--- docs/multimodal.md | 46 +- docs/multimodal/llama-mtmd-cli-ep.md | 433 ------------------ tools/mtmd/CMakeLists.txt | 69 ++- tools/mtmd/ep-vision-wrapper.cpp | 216 ++++++++- .../{mtmd-cli-ep.cpp => mtmd-cli-smt.cpp} | 71 ++- tools/mtmd/mtmd-cli.cpp | 25 + tools/mtmd/preprocess_qwen3vl.py | 386 ---------------- tools/server/CMakeLists.txt | 41 +- tools/server/README.md | 20 - tools/server/server-common.cpp | 12 +- tools/server/server-common.h | 4 +- tools/server/server-context.cpp | 44 +- tools/server/server-ep-vision.cpp | 22 +- 17 files changed, 467 insertions(+), 1097 deletions(-) delete mode 100644 docs/multimodal/llama-mtmd-cli-ep.md rename tools/mtmd/{mtmd-cli-ep.cpp => mtmd-cli-smt.cpp} (93%) delete mode 100644 tools/mtmd/preprocess_qwen3vl.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 244f4cb49825..36761bf98358 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -116,6 +116,11 @@ option(LLAMA_TESTS_INSTALL "llama: install tests" # 3rd party libs option(LLAMA_OPENSSL "llama: use openssl to support HTTPS" ON) option(LLAMA_LLGUIDANCE "llama-common: include LLGuidance library for structured output in common utils" OFF) +option(LLAMA_SERVER_SMT_VISION "llama: enable SpacemiT multimodal SMT extensions" OFF) + +if (LLAMA_SERVER_SMT_VISION) + add_compile_definitions(LLAMA_SERVER_SMT_VISION=1) +endif() # Required for relocatable CMake package diff --git a/common/arg.cpp b/common/arg.cpp index ae762ffc13ed..844c3a2b865f 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -2197,23 +2197,25 @@ common_params_context common_params_parser_init(common_params & params, llama_ex params.mmproj_use_gpu = value; } ).set_examples(mmproj_examples).set_env("LLAMA_ARG_MMPROJ_OFFLOAD")); +#if defined(LLAMA_SERVER_SMT_VISION) add_opt(common_arg( - {"--vision-backend"}, "{auto|mtmd|ep}", + {"--vision-backend"}, "{auto|mtmd|smt}", string_format("multimodal backend selection (default: %s)", params.vision_backend.c_str()), [](common_params & params, const std::string & value) { - if (value != "auto" && value != "mtmd" && value != "ep") { - throw std::invalid_argument("vision-backend must be one of: auto, mtmd, ep"); + if (value != "auto" && value != "mtmd" && value != "smt") { + throw std::invalid_argument("vision-backend must be one of: auto, mtmd, smt"); } params.vision_backend = value; } - ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_VISION_BACKEND")); + ).set_examples({LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_MTMD}).set_env("LLAMA_ARG_VISION_BACKEND")); add_opt(common_arg( - {"--ep-config-dir"}, "DIR", - "path to EP config directory (config.json + ONNX model files)", + {"--smt-config-dir"}, "DIR", + "path to SMT config directory (config.json + ONNX model files)", [](common_params & params, const std::string & value) { - params.ep_config_dir = value; + params.smt_config_dir = value; } - ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_EP_CONFIG_DIR")); + ).set_examples({LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_MTMD}).set_env("LLAMA_ARG_SMT_CONFIG_DIR")); +#endif add_opt(common_arg( {"--image", "--audio"}, "FILE", "path to an image or audio file. use with multimodal models, use comma-separated values for multiple files\n", diff --git a/common/common.h b/common/common.h index d92eeb382113..272c381ea8d1 100644 --- a/common/common.h +++ b/common/common.h @@ -556,8 +556,8 @@ struct common_params { struct common_params_model mmproj; bool mmproj_use_gpu = true; // use GPU for multimodal model bool no_mmproj = false; // explicitly disable multimodal model - std::string vision_backend = "auto"; // multimodal backend: auto|mtmd|ep - std::string ep_config_dir; // EP config dir (config.json + ONNX) + std::string vision_backend = "auto"; // multimodal backend: auto|mtmd|smt + std::string smt_config_dir; // SMT config dir (config.json + ONNX) std::vector image; // path to image file(s) int image_min_tokens = -1; int image_max_tokens = -1; diff --git a/docs/build-riscv64-spacemit.md b/docs/build-riscv64-spacemit.md index b44742758fe9..3def00f89256 100644 --- a/docs/build-riscv64-spacemit.md +++ b/docs/build-riscv64-spacemit.md @@ -49,24 +49,9 @@ export RISCV_ROOT_PATH_IME1={your RISC-V compiler path} ${QEMU_ROOT_PATH}/bin/qemu-riscv64 -L ${RISCV_ROOT_PATH_IME1}/sysroot -cpu max,vlen=256,elen=64,vext_spec=v1.0 ${PWD}/build/bin/llama-cli -m ${PWD}/models/Qwen2.5-0.5B-Instruct-Q4_0.gguf -t 1 ~~~ - -## Quantization Support For Matrix - -| Quantization Type | X60 | A100 | -| ---: | ---: | ---: | -| Q2_K | | :heavy_check_mark: | -| Q3_K | | :heavy_check_mark: | -| Q4_0 | :heavy_check_mark: | :heavy_check_mark: | -| Q4_1 | :heavy_check_mark: | :heavy_check_mark: | -| Q4_K | :heavy_check_mark: | :heavy_check_mark: | -| Q5_0 | | :heavy_check_mark: | -| Q5_1 | | :heavy_check_mark: | -| Q5_K | | :heavy_check_mark: | -| Q6_K | | :heavy_check_mark: | -| Q8_0 | | :heavy_check_mark: | - - ## Performance +#### Quantization Support For Matrix + * Spacemit(R) X60 ~~~ model name : Spacemit(R) X60 @@ -77,13 +62,36 @@ mvendorid : 0x710 marchid : 0x8000000058000001 ~~~ -| model | size | params | backend | threads | n_ubatch | fa | mmap | test | t/s | -| ------------------------------ | ---------: | ---------: | ---------- | ------: | -------: | -: | ---: | --------------: | -------------------: | -| qwen35 2B Q4_1 | 1.19 GiB | 1.88 B | CPU | 4 | 128 | 1 | 0 | pp128 | 10.32 ± 0.02 | -| qwen35 2B Q4_1 | 1.19 GiB | 1.88 B | CPU | 4 | 128 | 1 | 0 | tg128 | 3.07 ± 0.01 | -| qwen3 0.6B Q4_0 | 358.78 MiB | 596.05 M | CPU | 4 | 128 | 1 | 0 | pp128 | 49.15 ± 0.25 | -| qwen3 0.6B Q4_0 | 358.78 MiB | 596.05 M | CPU | 4 | 128 | 1 | 0 | tg128 | 11.73 ± 0.02 | - +Q4_0 +| Model | Size | Params | backend | threads | test | t/s | +| -----------| -------- | ------ | ------- | ------- | ---- |------| +Qwen2.5 0.5B |403.20 MiB|630.17 M| cpu | 4 | pp512|64.12 ± 0.26| +Qwen2.5 0.5B |403.20 MiB|630.17 M| cpu | 4 | tg128|10.03 ± 0.01| +Qwen2.5 1.5B |1011.16 MiB| 1.78 B | cpu | 4 | pp512|24.16 ± 0.02| +Qwen2.5 1.5B |1011.16 MiB| 1.78 B | cpu | 4 | tg128|3.83 ± 0.06| +Qwen2.5 3B | 1.86 GiB | 3.40 B | cpu | 4 | pp512|12.08 ± 0.02| +Qwen2.5 3B | 1.86 GiB | 3.40 B | cpu | 4 | tg128|2.23 ± 0.02| + +Q4_1 +| Model | Size | Params | backend | threads | test | t/s | +| -----------| -------- | ------ | ------- | ------- | ---- |------| +Qwen2.5 0.5B |351.50 MiB|494.03 M| cpu | 4 | pp512|62.07 ± 0.12| +Qwen2.5 0.5B |351.50 MiB|494.03 M| cpu | 4 | tg128|9.91 ± 0.01| +Qwen2.5 1.5B |964.06 MiB| 1.54 B | cpu | 4 | pp512|22.95 ± 0.25| +Qwen2.5 1.5B |964.06 MiB| 1.54 B | cpu | 4 | tg128|4.01 ± 0.15| +Qwen2.5 3B | 1.85 GiB | 3.09 B | cpu | 4 | pp512|11.55 ± 0.16| +Qwen2.5 3B | 1.85 GiB | 3.09 B | cpu | 4 | tg128|2.25 ± 0.04| + + +Q4_K +| Model | Size | Params | backend | threads | test | t/s | +| -----------| -------- | ------ | ------- | ------- | ---- |------| +Qwen2.5 0.5B |462.96 MiB|630.17 M| cpu | 4 | pp512|9.29 ± 0.05| +Qwen2.5 0.5B |462.96 MiB|630.17 M| cpu | 4 | tg128|5.67 ± 0.04| +Qwen2.5 1.5B | 1.04 GiB | 1.78 B | cpu | 4 | pp512|10.38 ± 0.10| +Qwen2.5 1.5B | 1.04 GiB | 1.78 B | cpu | 4 | tg128|3.17 ± 0.08| +Qwen2.5 3B | 1.95 GiB | 3.40 B | cpu | 4 | pp512|4.23 ± 0.04| +Qwen2.5 3B | 1.95 GiB | 3.40 B | cpu | 4 | tg128|1.73 ± 0.00| * Spacemit(R) A100 ~~~ @@ -95,39 +103,29 @@ marchid : 0x8000000041000002 mimpid : 0x10000000d5686200 hart isa : rv64imafdcv_zicbom_zicbop_zicboz_zicntr_zicond_zicsr_zifencei_zihintntl_zihintpause_zihpm_zimop_zaamo_zalrsc_zawrs_zfa_zfh_zfhmin_zca_zcb_zcd_zcmop_zba_zbb_zbc_zbs_zkt_zvbb_zvbc_zve32f_zve32x_zve64d_zve64f_zve64x_zvfh_zvfhmin_zvkb_zvkg_zvkned_zvknha_zvknhb_zvksed_zvksh_zvkt_smaia_smstateen_ssaia_sscofpmf_sstc_svinval_svnapot_svpbmt_sdtrig ~~~ -| model | size | params | backend | threads | n_ubatch | fa | mmap | test | t/s | -| ------------------------------ | ---------: | ---------: | ---------- | ------: | -------: | -: | ---: | --------------: | -------------------: | -| qwen3 0.6B Q4_0 | 358.78 MiB | 596.05 M | CPU | 8 | 128 | 1 | 0 | pp128 | 565.83 ± 0.31 | -| qwen3 0.6B Q4_0 | 358.78 MiB | 596.05 M | CPU | 8 | 128 | 1 | 0 | tg128 | 55.77 ± 0.02 | -| qwen3 4B Q4_0 | 2.21 GiB | 4.02 B | CPU | 8 | 128 | 1 | 0 | pp128 | 79.74 ± 0.04 | -| qwen3 4B Q4_0 | 2.21 GiB | 4.02 B | CPU | 8 | 128 | 1 | 0 | tg128 | 11.29 ± 0.00 | -| qwen3moe 30B.A3B Q4_0 | 16.18 GiB | 30.53 B | CPU | 8 | 128 | 1 | 0 | pp128 | 57.88 ± 0.31 | -| qwen3moe 30B.A3B Q4_0 | 16.18 GiB | 30.53 B | CPU | 8 | 128 | 1 | 0 | tg128 | 12.79 ± 0.00 | -| qwen35 2B Q4_1 | 1.19 GiB | 1.88 B | CPU | 8 | 128 | 1 | 0 | pp128 | 115.23 ± 0.04 | -| qwen35 2B Q4_1 | 1.19 GiB | 1.88 B | CPU | 8 | 128 | 1 | 0 | tg128 | 16.49 ± 0.01 | -| gemma4 E4B Q4_K - Medium | 4.76 GiB | 7.52 B | CPU | 8 | 128 | 1 | 0 | pp128 | 21.13 ± 0.01 | -| gemma4 E4B Q4_K - Medium | 4.76 GiB | 7.52 B | CPU | 8 | 128 | 1 | 0 | tg128 | 5.66 ± 0.00 | - -## Build and run with EP acceleration - -To enable the Spacemit EP vision backend in addition to the default CPU build, the build must also include the EP-related CMake options and point to both the `spacemit-ep` source tree and the `onnxruntime` build tree. + +## Build and run with SMT acceleration + +To enable the SpacemiT multimodal SMT extensions in addition to the default CPU build, turn on the SMT build switch and point it to a single `SPACEMIT_ORT_DIR` bundle containing: + +- `include/` +- `lib/` +- `samples/` + +`LLAMA_SERVER_SMT_VISION` is `OFF` by default. If it is not enabled, the build remains the native llama.cpp build without SpacemiT SMT extensions. ### Build -The EP-enabled build needs these additional CMake definitions: +The SMT-enabled build needs these additional CMake definitions: -- `-DMTMD_BUILD_EP_CLI=ON` -- `-DLLAMA_SERVER_EP_VISION=ON` -- `-DSPACEMIT_EP_DIR=` -- `-DONNXRUNTIME_INC_DIR=/include/onnxruntime` -- `-DONNXRUNTIME_LIB_DIR=/build/Linux/rv64/Release` +- `-DLLAMA_SERVER_SMT_VISION=ON` +- `-DSPACEMIT_ORT_DIR=` Example full build command: ```bash -export SPACEMIT_EP_DIR=/path/to/spacemit-ep -export ONNXRUNTIME_DIR=/path/to/onnxruntime -export LD_LIBRARY_PATH=${ONNXRUNTIME_DIR}/build/Linux/rv64/Release:${LD_LIBRARY_PATH} +export SPACEMIT_ORT_DIR=/path/to/spacemit-ort +export LD_LIBRARY_PATH=${SPACEMIT_ORT_DIR}/lib:${LD_LIBRARY_PATH} cmake -B build \ -DCMAKE_BUILD_TYPE=Release \ @@ -142,11 +140,8 @@ cmake -B build \ -DGGML_RV_ZBA=ON \ -DCMAKE_TOOLCHAIN_FILE=${PWD}/cmake/riscv64-spacemit-linux-gnu-gcc.cmake \ -DCMAKE_INSTALL_PREFIX=build/installed \ - -DMTMD_BUILD_EP_CLI=ON \ - -DLLAMA_SERVER_EP_VISION=ON \ - -DSPACEMIT_EP_DIR=${SPACEMIT_EP_DIR} \ - -DONNXRUNTIME_INC_DIR=${ONNXRUNTIME_DIR}/include/onnxruntime \ - -DONNXRUNTIME_LIB_DIR=${ONNXRUNTIME_DIR}/build/Linux/rv64/Release + -DLLAMA_SERVER_SMT_VISION=ON \ + -DSPACEMIT_ORT_DIR=${SPACEMIT_ORT_DIR} cmake --build build --parallel $(nproc) --config Release @@ -157,29 +152,54 @@ popd ### Run -At runtime, EP-enabled binaries need to find both ONNX Runtime and the Spacemit EP provider shared library. Make sure `LD_LIBRARY_PATH` includes: +At runtime, SMT-enabled binaries need to find the libraries under `SPACEMIT_ORT_DIR/lib`. Make sure `LD_LIBRARY_PATH` includes: -- the ONNX Runtime library directory -- the Spacemit EP library directory +- the SMT bundle library directory - the installed llama.cpp library directory if running from an installed package Example: ```bash -export LD_LIBRARY_PATH=/path/to/onnxruntime/build/Linux/rv64/Release:/path/to/spacemit-ep/build/rv64/Release/installed/lib:./build/installed/lib:${LD_LIBRARY_PATH} +export LD_LIBRARY_PATH=/path/to/spacemit-ort/lib:./build/installed/lib:${LD_LIBRARY_PATH} ``` -For `llama-server`, also pass the EP config directory at runtime, for example: +For `llama-server`, also pass the SMT config directory at runtime, for example: ```bash ./build/bin/llama-server \ -m /path/to/model.gguf \ - --vision-backend ep \ - --ep-config-dir /path/to/ep-config-dir + --vision-backend smt \ + --smt-config-dir /path/to/smt-config-dir +``` + +For `llama-mtmd-cli`, use the same backend selector and config directory: + +```bash +./build/bin/llama-mtmd-cli \ + -m /path/to/model.gguf \ + --vision-backend smt \ + --smt-config-dir /path/to/smt-config-dir \ + --image /path/to/input.jpg \ + -p "<__media__>Describe this image." ``` Notes: -- `--ep-config-dir` should point to the directory containing `config.json` and the EP vision ONNX model files. -- If `libspacemit_ep.so` is missing from `LD_LIBRARY_PATH`, EP session initialization will fail at runtime. -- If `libonnxruntime.so` is missing from `LD_LIBRARY_PATH`, the EP-enabled binary will not run successfully. +- `--smt-config-dir` should point to the directory containing `config.json` and the SMT vision ONNX model files. +- If `libspacemit_ep.so` is missing from `LD_LIBRARY_PATH`, SMT session initialization will fail at runtime. +- If `libonnxruntime.so` is missing from `LD_LIBRARY_PATH`, the SMT-enabled binary will not run successfully. +- In the current SMT integration, `config.json` only needs the fields that are actually consumed by `llama-server` / `llama-mtmd-cli`: `architectures`, `vision_model.model_path`, and `text_model.hidden_size`. A minimal example is: + +```json +{ + "architectures": [ + "Qwen3VL" + ], + "vision_model": { + "model_path": "./qwen3_vl_vision.onnx" + }, + "text_model": { + "hidden_size": 896 + } +} +``` diff --git a/docs/multimodal.md b/docs/multimodal.md index b85ca10aa421..33d1df33c3bb 100644 --- a/docs/multimodal.md +++ b/docs/multimodal.md @@ -1,8 +1,7 @@ # Multimodal -llama.cpp supports multimodal input via `libmtmd`. Currently, there are 3 tools support this feature: +llama.cpp supports multimodal input via `libmtmd`. Currently, there are 2 tools support this feature: - [llama-mtmd-cli](../tools/mtmd/README.md) -- [llama-mtmd-cli-ep](./multimodal/llama-mtmd-cli-ep.md) (Spacemit EP ONNX vision backend) - [llama-server](../tools/server/README.md) via OpenAI-compatible `/chat/completions` API Currently, we support **image** and **audio** input. Audio is highly experimental and may have reduced quality. @@ -41,49 +40,6 @@ llama-server -hf ggml-org/gemma-3-4b-it-GGUF --no-mmproj-offload > - Dots.OCR: https://github.com/ggml-org/llama.cpp/pull/17575 > - HunyuanOCR: https://github.com/ggml-org/llama.cpp/pull/21395 -## Spacemit EP vision backend - -The EP vision backend is an alternative multimodal path for supported deployments (for example FastVLM and Qwen3VL with Spacemit EP ONNX vision models). - -- For detailed `llama-mtmd-cli-ep` behavior and options, see: [llama-mtmd-cli-ep.md](./multimodal/llama-mtmd-cli-ep.md) -- For server options, see `llama-server --help` (`--vision-backend ep`, `--ep-config-dir `) - -### `llama-mtmd-cli-ep` example - -```sh -llama-mtmd-cli-ep \ - -m /path/to/qwen3vl-30b-text-q4_1.gguf \ - --mmproj /path/to/ep_config_dir \ - --image /path/to/input.jpg \ - -p "<__media__>Describe this image." \ - -c 1024 -b 128 -ctk q4_0 -ctv q8_0 -``` - -### `llama-server` EP example - -```sh -llama-server \ - -m /path/to/qwen3vl-30b-text-q4_1.gguf \ - --vision-backend ep \ - --ep-config-dir /path/to/ep_config_dir \ - --media-path /path/to/media_root/ \ - -c 1024 -b 128 -ctk q4_0 -ctv q8_0 --host 0.0.0.0 --port 8080 -``` - -With EP backend, image input can be sent as regular image files (`.jpg`, `.png`, etc.) or preprocessed `.bin` tensors. - -### Qwen3VL-30B practical note - -`qwen3vl-30b` is very large. In practice, you should constrain context length and KV cache quantization. - -One known workable configuration is: - -```sh --c 1024 -b 128 -ctk q4_0 -ctv q8_0 -``` - -Other configurations are possible and should be tuned per hardware and workload. - ## Pre-quantized models These are ready-to-use models, most of them come with `Q4_K_M` quantization by default. They can be found at the Hugging Face page of the ggml-org: https://huggingface.co/collections/ggml-org/multimodal-ggufs-68244e01ff1f39e5bebeeedc diff --git a/docs/multimodal/llama-mtmd-cli-ep.md b/docs/multimodal/llama-mtmd-cli-ep.md deleted file mode 100644 index 0af9b9f08555..000000000000 --- a/docs/multimodal/llama-mtmd-cli-ep.md +++ /dev/null @@ -1,433 +0,0 @@ -# llama-mtmd-cli-ep 使用文档 - -`llama-mtmd-cli-ep` 是基于 `llama.cpp` 的多模态命令行推理工具,专为 Spacemit EP ONNX 视觉引擎设计。 - -- **文本推理**:由 llama.cpp 加载 GGUF 格式的文本模型完成 -- **视觉编码**:由 Spacemit EP ONNX 引擎完成,支持直接输入 `jpg/png`(内部预处理)或预处理的 `.bin` -- **运行模式**:支持单轮推理和交互聊天两种模式 - -> **状态说明(重要)**: -> 目前仅在 **FastVLM** 与 **Qwen3VL** 方案上做过端到端实测。文档中其它“架构匹配”内容仅表示代码里存在对应 token 匹配逻辑,不代表已经过完整验证。 - ---- - -## 目录 - -- [1. 与原生 llama-mtmd-cli 的区别](#1-与原生-llama-mtmd-cli-的区别) -- [2. 前置条件](#2-前置条件) -- [3. 命令行参数说明](#3-命令行参数说明) -- [4. 单轮推理模式](#4-单轮推理模式) -- [5. 交互聊天模式](#5-交互聊天模式) -- [6. 环境变量](#6-环境变量) -- [7. 验证范围与兼容性说明](#7-验证范围与兼容性说明) -- [8. 板端运行建议](#8-板端运行建议) -- [9. 常见报错与排查](#9-常见报错与排查) -- [10. 当前限制](#10-当前限制) - ---- - -## 1. 与原生 llama-mtmd-cli 的区别 - -| 对比项 | 原生 `llama-mtmd-cli` | EP 版 `llama-mtmd-cli-ep` | -|--------|----------------------|--------------------------| -| `--mmproj` 指向 | `mmproj.gguf` 文件 | EP 配置目录(含 `config.json` + ONNX 模型) | -| `--image` 格式 | jpg / png 等常见图片格式 | `jpg/png`(内部预处理)或预处理后的二进制文件(`.bin`) | -| 视觉编码后端 | CLIP/GGUF | Spacemit EP ONNX 引擎 | -| 音频支持 | 支持 | 不支持(仅视觉) | - ---- - -## 2. 前置条件 - -运行前需要准备以下文件: - -1. **文本模型**(GGUF 格式) - - 已验证示例:`fastvlm-text-0.5B-Q4_1.gguf`、`qwen3vl-30b-text-q4_1.gguf` - -2. **EP 视觉配置目录**,目录内至少包含: - - `config.json`:视觉模型配置,其中的 `hidden_size` **必须**与文本模型的 `n_embd` 一致 - - 视觉 ONNX 模型文件(如 `fastvlm_vision.f16.onnx`、`qwen3_vl_vision.q_replaceneg.onnx`) - -3. **图像输入** - - 支持直接传入原始图像文件(如 `input.jpg`、`input.png`) - - 也支持传入预处理后的二进制文件(如 `input.bin`、`input2.bin`) - -> **注意**:如果 `config.json` 中的 `hidden_size` 与文本模型的 `n_embd` 不一致,程序会报错并退出。 - ---- - -## 3. 命令行参数说明 - -### 3.1 必需参数 - -| 参数 | 格式 | 说明 | -|------|------|------| -| `-m` | `-m ` | 文本模型文件路径(GGUF 格式)。这是 LLM 推理的核心模型。 | -| `--mmproj` (或 `-mm`) | `--mmproj <目录路径>` | EP 视觉配置目录路径,目录内需包含 `config.json` 和 ONNX 视觉模型。也可通过环境变量 `EP_CONFIG_DIR` 替代。 | - -### 3.2 模式控制参数 - -| 参数 | 格式 | 说明 | -|------|------|------| -| `--image` | `--image ` | 图像路径,支持 `jpg/png`(内部预处理)和预处理 `.bin`。支持两种方式指定多个图像:① 逗号分隔 `--image a.jpg,b.jpg`;② 重复参数 `--image a.jpg --image b.jpg`。当与 `-p` 同时提供时进入**单轮推理模式**。 | -| `-p` | `-p "<提示词>"` | 用户提示词。在提示词中使用 `<__media__>` 标记图像插入位置。当与 `--image` 同时提供时进入**单轮推理模式**。 | - -> 当 `--image` 和 `-p` **同时提供**时为单轮推理模式;否则进入交互聊天模式。 - -### 3.3 生成控制参数 - -| 参数 | 格式 | 说明 | -|------|------|------| -| `-n` | `-n <数量>` | 最大生成 token 数量。默认 `-1` 表示不限制(生成到 EOS 或手动中断)。 | -| `--temp` | `--temp <温度值>` | 采样温度,控制生成随机性。值越高输出越随机,值越低越确定。 | -| `--top-k` | `--top-k ` | Top-K 采样参数。 | -| `--top-p` | `--top-p

` | Top-P(核采样)参数。 | - -### 3.4 上下文与模板参数 - -| 参数 | 格式 | 说明 | -|------|------|------| -| `-c` | `-c <大小>` | 上下文窗口大小(token 数)。 | -| `-b` | `-b <批大小>` | 批处理大小,影响推理吞吐。 | -| `-t` | `-t <线程数>` | 推理使用的 CPU 线程数。 | -| `--chat-template` | `--chat-template <名称>` | 指定聊天模板名称。如不指定,使用模型内置模板。 | -| `--system-prompt` | `--system-prompt "<文本>"` | 系统提示词。会在对话开始前作为 system 角色消息注入。 | -| `--jinja` | `--jinja` | 启用 Jinja 模板渲染聊天格式。 | - -### 3.5 关于 `<__media__>` 标记 - -`<__media__>` 是提示词中的图像占位标记,用于指定图像嵌入的插入位置: - -- 每个 `<__media__>` 按顺序对应一个 `--image` 指定的图像文件 -- `<__media__>` 的数量**必须**与图像文件数量一致 -- 如果提示词中未包含 `<__media__>`,程序会自动在提示词前面为每张图像添加一个 -- 旧标记 `<__image__>` 仍然兼容,会被自动替换为 `<__media__>` - ---- - -## 4. 单轮推理模式 - -### 4.1 触发条件 - -同时提供 `--image` 和 `-p` 参数时,进入单轮推理模式。程序处理完一次请求后自动退出。 - -### 4.2 基本用法 - -```bash -llama-mtmd-cli-ep \ - -m <模型文件.gguf> \ - --mmproj \ - --image <图像.bin> \ - -p "<提示词>" \ - -n <最大token数> -``` - -### 4.3 单图推理示例 - -```bash -llama-mtmd-cli-ep \ - -m ./multimodal_llm_files/fastvlm-text-0.5B-Q4_1.gguf \ - --mmproj ./multimodal_llm_files \ - --image ./multimodal_llm_files/input.bin \ - -p "<__media__>请描述这张图片的内容" \ - -n 128 -``` - -提示词中的 `<__media__>` 会被替换为 `input.bin` 编码后的图像嵌入。如果省略 `<__media__>`,程序会自动在提示词前面插入。 - -### 4.4 多图推理示例 - -多图推理时,`<__media__>` 数量必须与图像数量一致。 - -**方式 A:逗号分隔图像路径** - -```bash -llama-mtmd-cli-ep \ - -m ./multimodal_llm_files/fastvlm-text-0.5B-Q4_1.gguf \ - --mmproj ./multimodal_llm_files \ - --image ./multimodal_llm_files/input.bin,./multimodal_llm_files/input2.bin \ - -p "<__media__>先描述第一张图片,再结合<__media__>比较第二张图片的差异" \ - -n 256 -``` - -**方式 B:重复 `--image` 参数** - -```bash -llama-mtmd-cli-ep \ - -m ./multimodal_llm_files/fastvlm-text-0.5B-Q4_1.gguf \ - --mmproj ./multimodal_llm_files \ - --image ./multimodal_llm_files/input.bin \ - --image ./multimodal_llm_files/input2.bin \ - -p "<__media__>先描述第一张图片,再结合<__media__>比较第二张图片的差异" \ - -n 256 -``` - -### 4.5 带系统提示词的推理 - -```bash -llama-mtmd-cli-ep \ - -m ./multimodal_llm_files/fastvlm-text-0.5B-Q4_1.gguf \ - --mmproj ./multimodal_llm_files \ - --image ./multimodal_llm_files/input.bin \ - --system-prompt "你是一个专业的图像分析助手,请用中文详细描述图片内容。" \ - -p "<__media__>请分析这张图" \ - -n 256 -``` - -### 4.6 处理流程 - -1. 加载文本模型和 EP 视觉引擎 -2. 如果有系统提示词,先评估系统消息 -3. 检查提示词中是否包含 `<__media__>`,如果没有则自动在前面为每张图片添加 -4. 将提示词按 `<__media__>` 分割为文本块和图像块 -5. 依次处理每个块: - - **文本块**:tokenize 后送入 LLM 解码 - - **图像块**:通过 EP 视觉引擎编码为嵌入向量,注入图像边界 token 后送入 LLM -6. 采样生成响应,直到遇到 EOS token 或达到最大 token 数 -7. 输出响应并退出 - ---- - -## 5. 交互聊天模式 - -### 5.1 触发条件 - -当 `--image` 和 `-p` **未同时提供**时,进入交互聊天模式。程序显示提示符 `>` 等待用户输入。 - -### 5.2 启动命令 - -```bash -llama-mtmd-cli-ep \ - -m ./multimodal_llm_files/fastvlm-text-0.5B-Q4_1.gguf \ - --mmproj ./multimodal_llm_files -``` - -启动后会显示: - -``` -Running in chat mode (EP vision), available commands: - /image load an image (.jpg/.png/...) or preprocessed .bin - /clear clear the chat history - /quit or /exit exit the program -``` - -### 5.3 聊天命令 - -| 命令 | 说明 | -|------|------| -| `/image ` | 加载一个图像文件(`jpg/png/...`)或预处理 `.bin`,并在当前输入中追加一个 `<__media__>` 标记。可以在发送文本前多次使用来加载多张图片。 | -| `/clear` | 清空聊天历史和上下文,恢复到初始状态。如有系统提示词会重新评估。 | -| `/quit` 或 `/exit` | 退出程序。 | -| `Ctrl+C` | 中断当前生成。再按一次 `Ctrl+C` 退出程序。 | -| 其他文本 | 作为用户消息发送给模型,触发模型生成响应。 | - -### 5.4 交互示例 - -#### 纯文本聊天 - -``` -> 你好,请介绍一下你自己 -你好!我是一个多模态AI助手,可以理解文本和图像... - -> 1+1等于几? -1+1等于2。 -``` - -#### 图文聊天(先加载图片,再提问) - -``` -> /image ./multimodal_llm_files/input.bin -./multimodal_llm_files/input.bin image binary loaded - -> 请描述这张图片的内容 -这张图片展示了... - -> 图片中有几个人? -图片中有... -``` - -#### 多图聊天 - -``` -> /image ./multimodal_llm_files/input.bin -./multimodal_llm_files/input.bin image binary loaded - -> /image ./multimodal_llm_files/input2.bin -./multimodal_llm_files/input2.bin image binary loaded - -> 比较这两张图片的区别 -第一张图片...第二张图片... - -> /clear -Chat history cleared -``` - -### 5.5 聊天模式工作流程 - -1. 用户输入 `/image `:图像路径加入待处理队列,`<__media__>` 标记追加到当前消息内容 -2. 用户输入普通文本:文本追加到当前消息内容,触发推理 -3. 推理时将消息通过聊天模板格式化,分块处理文本和图像 -4. 生成的响应存入聊天历史,支持多轮上下文 -5. `/clear` 会清空聊天历史和 KV Cache,重新开始对话 - ---- - -## 6. 环境变量 - -### 6.1 `EP_CONFIG_DIR` - -当未通过 `--mmproj` 指定 EP 配置目录时,程序会尝试从此环境变量读取。 - -```bash -export EP_CONFIG_DIR=./multimodal_llm_files -llama-mtmd-cli-ep -m text.gguf --image input.bin -p "描述图片" -``` - -### 6.2 `MTMD_EP_IMAGE_BOUNDARY` - -控制图像边界 token 的注入策略。图像边界 token(如 `<|vision_start|>` / `<|vision_end|>`)用于告诉 LLM 图像嵌入的起止位置。 - -| 值 | 说明 | -|----|------| -| `native`(默认,推荐) | 根据模型架构名称(如 qwen2vl、gemma3 等)自动匹配对应的边界 token | -| `auto` 或 `detect` | 不依赖架构名称,尝试从词汇表中探测已知的边界 token 对 | -| `none`、`off` 或 `0` | 不注入任何图像边界 token | - -```bash -export MTMD_EP_IMAGE_BOUNDARY=native -``` - -### 6.3 `MTMD_EP_MEDIA_ANCHOR` - -控制多图提示词的锚点规范化。启用后会为多图提示词自动添加图像编号标注,帮助模型区分多张图片。 - -| 值 | 说明 | -|----|------| -| `off`(默认) | 不进行规范化 | -| `auto` | 仅对已知支持的架构(如 LLaVA-Qwen2)应用规范化 | -| `on`、`1` 或 `true` | 对所有多图提示词强制应用规范化 | - -规范化效果示例: - -``` -# 原始提示词: -<__media__>先描述第一张,再结合<__media__>比较第二张差异 - -# 规范化后: -Please align images by order index. Image #1 maps to the first media slot, Image #2 to the second, and so on. -[Image 1 Begin] -<__media__> -[Image 1 End] -先描述第一张,再结合 -[Image 2 Begin] -<__media__> -[Image 2 End] -比较第二张差异 -``` - ---- - -## 7. 验证范围与兼容性说明 - -### 7.1 已完成端到端验证的模型 - -当前仅验证了以下两类方案: - -| 方案 | `config.json` 中常见 `architectures` | 状态 | -|------|--------------------------------------|------| -| FastVLM | `LlavaQwen2ForCausalLM` | 已验证 | -| Qwen3VL | `Qwen3VL` | 已验证 | - -### 7.2 图像边界 token 匹配规则(代码层) - -EP 版工具会根据文本模型架构名称匹配图像边界 token。下表表示**代码中存在匹配逻辑**,不等同于“已完成端到端验证”: - -| 模型架构 | 图像开始 token | 图像结束 token | -|---------|---------------|---------------| -| Qwen2-VL / Qwen2.5-VL / Qwen3-VL / YoutuVL | `<\|vision_start\|>` | `<\|vision_end\|>` | -| Llama4 | `<\|image_start\|>` | `<\|image_end\|>` | -| Gemma3 | `` | `` | -| InternVL | `` | `` | -| GLM-4V | `<\|begin_of_image\|>` | `<\|end_of_image\|>` | -| PaddleOCR | `<\|IMAGE_START\|>` | `<\|IMAGE_END\|>` | -| LightonOCR | `<\|im_start\|>` | `<\|im_end\|>` | - -如果你的模型架构不在上面列表中,可以尝试设置 `MTMD_EP_IMAGE_BOUNDARY=auto` 让程序自动探测,或设置为 `none` 跳过边界 token 注入。 - -> 对于未验证模型,建议先做小样本功能验证(单图、短上下文、固定提示词),再进行批量测试。 - ---- - -## 8. 板端运行建议 - -### 8.1 设置动态库路径 - -```bash -export LD_LIBRARY_PATH=./llamainstall/lib/:ort_installed/lib/:installed/lib/ -``` - -### 8.2 记录运行日志 - -建议将输出保存到日志文件,方便调试: - -```bash -LOG_FILE=./ep_run_$(date +%Y%m%d_%H%M%S).log -llama-mtmd-cli-ep \ - -m ./multimodal_llm_files/fastvlm-text-0.5B-Q4_1.gguf \ - --mmproj ./multimodal_llm_files \ - --image ./multimodal_llm_files/input.bin \ - -p "<__media__>请描述这张图" \ - -n 128 \ - 2>&1 | tee "$LOG_FILE" -``` - -### 8.3 推理性能调优 - -- `-t <线程数>`:根据板端 CPU 核心数设置合理的线程数 -- `-b <批大小>`:增大批大小可以提高吞吐,但会增加内存占用 -- `-c <上下文大小>`:根据需要调整上下文窗口大小,减小可以节省内存 - ---- - -## 9. 常见报错与排查 - -### `Missing EP config directory` - -**原因**:未通过 `--mmproj` 指定 EP 配置目录,且环境变量 `EP_CONFIG_DIR` 也未设置。 - -**解决**:添加 `--mmproj <目录路径>` 或设置 `export EP_CONFIG_DIR=<目录路径>`。 - -### `Number of images (...) does not match number of media markers (...)` - -**原因**:提示词中 `<__media__>` 标记的数量与 `--image` 指定的图像文件数量不一致。 - -**解决**:确保每张图片对应一个 `<__media__>` 标记。例如两张图片需要两个 `<__media__>`。 - -### `model n_embd (...) != EP hidden_size (...)` - -**原因**:文本模型的嵌入维度与 EP 配置中的 `hidden_size` 不匹配。 - -**解决**:使用同一套模型导出的文本 GGUF 和 EP 视觉配置。 - -### `Invalid image embedding shape from EP` - -**原因**:EP 视觉引擎对图像的编码输出形状不正确。可能是 `.bin` 文件格式或来源不正确,或视觉 ONNX 模型文件有问题。 - -**解决**:检查 `.bin` 文件是否由正确的预处理工具生成,且与当前的 ONNX 视觉模型匹配。 - -### `Failed to decode token` / `Failed to decode text chunk` - -**原因**:LLM 解码过程中出错,可能是上下文窗口溢出或内存不足。 - -**解决**:尝试增大 `-c` 上下文大小,或减少输入图片数量。 - ---- - -## 10. 当前限制 - -- 仅支持视觉输入(图像),**不支持音频输入** -- 对于当前已验证链路,`fastvlm` 与 `qwen3vl` 支持直接输入 `jpg/png`(内部预处理)和 `.bin` -- 端到端仅在 FastVLM、Qwen3VL 上实测通过;其它模型请视为“未验证状态” -- 建议使用默认的环境变量配置以保持稳定: - - `MTMD_EP_IMAGE_BOUNDARY=native` - - `MTMD_EP_MEDIA_ANCHOR=off` diff --git a/tools/mtmd/CMakeLists.txt b/tools/mtmd/CMakeLists.txt index c467f5713ae3..d4564d07db55 100644 --- a/tools/mtmd/CMakeLists.txt +++ b/tools/mtmd/CMakeLists.txt @@ -6,8 +6,6 @@ add_library(mtmd mtmd.cpp mtmd-audio.cpp mtmd-image.cpp - ep-vision-preprocess.cpp - ep-vision-preprocess.h mtmd.h mtmd-helper.cpp mtmd-helper.h @@ -125,57 +123,50 @@ set_target_properties(llama-mtmd-debug PROPERTIES OUTPUT_NAME llama-mtmd-debug) target_link_libraries(llama-mtmd-debug PRIVATE llama-common mtmd Threads::Threads) target_compile_features(llama-mtmd-debug PRIVATE cxx_std_17) -# ============================================================ -# EP Vision variant of mtmd-cli -# Uses Spacemit EP ONNX vision engine instead of CLIP/GGUF -# ============================================================ -option(MTMD_BUILD_EP_CLI "Build mtmd-cli with Spacemit EP vision support" OFF) +if(LLAMA_SERVER_SMT_VISION) + if(NOT DEFINED SPACEMIT_ORT_DIR) + message(FATAL_ERROR "SPACEMIT_ORT_DIR must be set when LLAMA_SERVER_SMT_VISION=ON") + endif() + + set(SPACEMIT_ORT_INC_DIR "${SPACEMIT_ORT_DIR}/include") + set(SPACEMIT_ORT_LIB_DIR "${SPACEMIT_ORT_DIR}/lib") + set(SPACEMIT_ORT_SAMPLE_DIR "${SPACEMIT_ORT_DIR}/samples") -if(MTMD_BUILD_EP_CLI) - if(NOT DEFINED SPACEMIT_EP_DIR) - message(FATAL_ERROR "SPACEMIT_EP_DIR must be set when MTMD_BUILD_EP_CLI=ON") + if(NOT EXISTS "${SPACEMIT_ORT_SAMPLE_DIR}/spine_vision_engine.cc") + message(FATAL_ERROR "Could not find spine_vision_engine.cc in SPACEMIT_ORT_DIR='${SPACEMIT_ORT_DIR}'") endif() - if(NOT DEFINED ONNXRUNTIME_INC_DIR) - message(FATAL_ERROR "ONNXRUNTIME_INC_DIR must be set when MTMD_BUILD_EP_CLI=ON") + if(NOT EXISTS "${SPACEMIT_ORT_SAMPLE_DIR}/spine_llm_argparser.cc") + message(FATAL_ERROR "Could not find spine_llm_argparser.cc in SPACEMIT_ORT_DIR='${SPACEMIT_ORT_DIR}'") endif() - if(NOT DEFINED ONNXRUNTIME_LIB_DIR) - message(FATAL_ERROR "ONNXRUNTIME_LIB_DIR must be set when MTMD_BUILD_EP_CLI=ON") + + if(EXISTS "${SPACEMIT_ORT_LIB_DIR}/libonnxruntime.so") + set(ONNXRUNTIME_LIB "${SPACEMIT_ORT_LIB_DIR}/libonnxruntime.so") + elseif(EXISTS "${SPACEMIT_ORT_LIB_DIR}/libonnxruntime.a") + set(ONNXRUNTIME_LIB "${SPACEMIT_ORT_LIB_DIR}/libonnxruntime.a") + else() + message(FATAL_ERROR "Could not find libonnxruntime.{so,a} in SPACEMIT_ORT_DIR='${SPACEMIT_ORT_DIR}'") endif() - set(EP_TARGET llama-mtmd-cli-ep) - add_executable(${EP_TARGET} - mtmd-cli-ep.cpp + target_sources(${TARGET} PRIVATE + mtmd-cli-smt.cpp + ep-vision-preprocess.cpp ep-vision-wrapper.cpp - ${SPACEMIT_EP_DIR}/src/llm/spine_vision_engine.cc - ${SPACEMIT_EP_DIR}/src/llm/spine_llm_argparser.cc + ${SPACEMIT_ORT_SAMPLE_DIR}/spine_vision_engine.cc + ${SPACEMIT_ORT_SAMPLE_DIR}/spine_llm_argparser.cc ) - set_target_properties(${EP_TARGET} PROPERTIES OUTPUT_NAME llama-mtmd-cli-ep) - target_include_directories(${EP_TARGET} PRIVATE + target_include_directories(${TARGET} PRIVATE . ../.. ../../vendor - ${SPACEMIT_EP_DIR}/src/llm - ${ONNXRUNTIME_INC_DIR} + ${SPACEMIT_ORT_SAMPLE_DIR} + ${SPACEMIT_ORT_INC_DIR} ) - target_link_directories(${EP_TARGET} PRIVATE - ${ONNXRUNTIME_LIB_DIR} - ) - - target_link_libraries(${EP_TARGET} PRIVATE - llama-common - mtmd - llama - ggml - onnxruntime + target_link_libraries(${TARGET} PRIVATE + ${ONNXRUNTIME_LIB} dl - Threads::Threads ) - target_compile_features(${EP_TARGET} PRIVATE cxx_std_17) - - if(LLAMA_TOOLS_INSTALL) - install(TARGETS ${EP_TARGET} RUNTIME) - endif() + target_compile_definitions(${TARGET} PRIVATE LLAMA_SERVER_SMT_VISION=1) endif() diff --git a/tools/mtmd/ep-vision-wrapper.cpp b/tools/mtmd/ep-vision-wrapper.cpp index 3b4d3e17e858..d54bc2e55aa1 100644 --- a/tools/mtmd/ep-vision-wrapper.cpp +++ b/tools/mtmd/ep-vision-wrapper.cpp @@ -3,9 +3,9 @@ #include "ep-vision-wrapper.h" -#include "spine_llm_argparser.h" #include "spine_vision_engine.h" +#include #include #include #include @@ -14,8 +14,211 @@ namespace onnxruntime { const OrtApi * g_ort = NULL; } // namespace onnxruntime +namespace { + +struct smt_vision_config { + std::vector architectures; + std::string vision_model_path; + int64_t hidden_size = 0; +}; + +static std::string read_file_to_string(const std::string & path) { + std::ifstream file(path); + if (!file.is_open()) { + return {}; + } + + return std::string((std::istreambuf_iterator(file)), std::istreambuf_iterator()); +} + +static size_t find_closing_brace(const std::string & text, size_t start_pos) { + int depth = 0; + for (size_t index = start_pos; index < text.size(); ++index) { + if (text[index] == '{') { + ++depth; + } else if (text[index] == '}') { + --depth; + if (depth == 0) { + return index; + } + } + } + return std::string::npos; +} + +static std::string trim_ascii(std::string value) { + while (!value.empty() && std::isspace(static_cast(value.front()))) { + value.erase(value.begin()); + } + while (!value.empty() && std::isspace(static_cast(value.back()))) { + value.pop_back(); + } + return value; +} + +static std::string extract_string_value(const std::string & text, const std::string & key) { + const std::string marker = "\"" + key + "\""; + const size_t key_pos = text.find(marker); + if (key_pos == std::string::npos) { + return {}; + } + + const size_t colon_pos = text.find(':', key_pos + marker.size()); + if (colon_pos == std::string::npos) { + return {}; + } + + const size_t first_quote = text.find('"', colon_pos + 1); + if (first_quote == std::string::npos) { + return {}; + } + + const size_t second_quote = text.find('"', first_quote + 1); + if (second_quote == std::string::npos) { + return {}; + } + + return text.substr(first_quote + 1, second_quote - first_quote - 1); +} + +static int64_t extract_int64_value(const std::string & text, const std::string & key, int64_t default_value) { + const std::string marker = "\"" + key + "\""; + const size_t key_pos = text.find(marker); + if (key_pos == std::string::npos) { + return default_value; + } + + const size_t colon_pos = text.find(':', key_pos + marker.size()); + if (colon_pos == std::string::npos) { + return default_value; + } + + size_t value_start = colon_pos + 1; + while (value_start < text.size() && std::isspace(static_cast(text[value_start]))) { + ++value_start; + } + + size_t value_end = value_start; + if (value_end < text.size() && (text[value_end] == '-' || text[value_end] == '+')) { + ++value_end; + } + while (value_end < text.size() && std::isdigit(static_cast(text[value_end]))) { + ++value_end; + } + + if (value_end == value_start) { + return default_value; + } + + try { + return std::stoll(text.substr(value_start, value_end - value_start)); + } catch (...) { + return default_value; + } +} + +static std::vector extract_string_array(const std::string & text, const std::string & key) { + std::vector values; + + const std::string marker = "\"" + key + "\""; + const size_t key_pos = text.find(marker); + if (key_pos == std::string::npos) { + return values; + } + + const size_t bracket_start = text.find('[', key_pos + marker.size()); + const size_t bracket_end = text.find(']', bracket_start == std::string::npos ? key_pos : bracket_start + 1); + if (bracket_start == std::string::npos || bracket_end == std::string::npos || bracket_end <= bracket_start) { + return values; + } + + std::string content = text.substr(bracket_start + 1, bracket_end - bracket_start - 1); + size_t pos = 0; + while (pos < content.size()) { + const size_t first_quote = content.find('"', pos); + if (first_quote == std::string::npos) { + break; + } + const size_t second_quote = content.find('"', first_quote + 1); + if (second_quote == std::string::npos) { + break; + } + values.push_back(content.substr(first_quote + 1, second_quote - first_quote - 1)); + pos = second_quote + 1; + } + + return values; +} + +static std::string normalize_path(const std::string & base_dir, const std::string & path) { + const std::string trimmed = trim_ascii(path); + if (trimmed.empty()) { + return {}; + } + if (!trimmed.empty() && trimmed.front() == '/') { + return trimmed; + } + return base_dir + "/" + trimmed; +} + +static bool load_smt_vision_config(const std::string & config_dir, smt_vision_config & config) { + const std::string config_path = config_dir + "/config.json"; + const std::string content = read_file_to_string(config_path); + if (content.empty()) { + std::cerr << "Error: Failed to read config file: " << config_path << "\n"; + return false; + } + + const size_t vision_start = content.find("\"vision_model\":"); + if (vision_start == std::string::npos) { + std::cerr << "Error: 'vision_model' section not found.\n"; + return false; + } + const size_t vision_block_start = content.find('{', vision_start); + const size_t vision_block_end = find_closing_brace(content, vision_block_start); + if (vision_block_start == std::string::npos || vision_block_end == std::string::npos) { + std::cerr << "Error: Invalid 'vision_model' block.\n"; + return false; + } + const std::string vision_block = content.substr(vision_block_start, vision_block_end - vision_block_start + 1); + + const size_t text_start = content.find("\"text_model\":"); + if (text_start == std::string::npos) { + std::cerr << "Error: 'text_model' section not found.\n"; + return false; + } + const size_t text_block_start = content.find('{', text_start); + const size_t text_block_end = find_closing_brace(content, text_block_start); + if (text_block_start == std::string::npos || text_block_end == std::string::npos) { + std::cerr << "Error: Invalid 'text_model' block.\n"; + return false; + } + const std::string text_block = content.substr(text_block_start, text_block_end - text_block_start + 1); + + config.vision_model_path = normalize_path(config_dir, extract_string_value(vision_block, "model_path")); + config.hidden_size = extract_int64_value(text_block, "hidden_size", 0); + config.architectures = extract_string_array(content, "architectures"); + + if (config.vision_model_path.empty()) { + std::cerr << "Error: Missing required key 'vision_model.model_path'.\n"; + return false; + } + if (config.hidden_size <= 0) { + std::cerr << "Error: Missing or invalid required key 'text_model.hidden_size'.\n"; + return false; + } + if (config.architectures.empty()) { + std::cerr << "Error: Missing required key 'architectures'.\n"; + return false; + } + + return true; +} + +} // namespace + struct ep_vision_context::impl { - onnxruntime::spacemit::SpineModelConfig config; + smt_vision_config config; std::unique_ptr vision_engine; std::string arch_name; }; @@ -28,8 +231,8 @@ std::unique_ptr ep_vision_context::create(const std::string & auto & d = *ctx->pimpl_; // 1. Load config from directory - if (!onnxruntime::spacemit::SpineLLMArgParser::LoadConfigFromDir(config_dir, d.config)) { - throw std::runtime_error("Failed to load EP config from: " + config_dir); + if (!load_smt_vision_config(config_dir, d.config)) { + throw std::runtime_error("Failed to load SMT config from: " + config_dir); } if (!d.config.architectures.empty()) { @@ -58,11 +261,12 @@ int64_t ep_vision_context::hidden_size() const { } int64_t ep_vision_context::vocab_size() const { - return pimpl_->config.vocab_size; + return 0; } const std::string & ep_vision_context::token_embedding_path() const { - return pimpl_->config.token_embedding_path; + static const std::string empty; + return empty; } const std::string & ep_vision_context::architecture() const { diff --git a/tools/mtmd/mtmd-cli-ep.cpp b/tools/mtmd/mtmd-cli-smt.cpp similarity index 93% rename from tools/mtmd/mtmd-cli-ep.cpp rename to tools/mtmd/mtmd-cli-smt.cpp index d6421c312b0c..c6b9cffe5b46 100644 --- a/tools/mtmd/mtmd-cli-ep.cpp +++ b/tools/mtmd/mtmd-cli-smt.cpp @@ -1,5 +1,5 @@ -// llama-mtmd-cli-ep: Multimodal CLI using Spacemit EP ONNX vision engine -// Based on mtmd-cli.cpp, replaces CLIP/GGUF vision encoding with EP's ONNX vision engine +// Multimodal CLI SMT backend using Spacemit EP ONNX vision engine +// Integrated into llama-mtmd-cli and selected via --vision-backend smt // LLM inference logic (loading, sampling, generation) is reused from the original mtmd-cli #include "arg.h" @@ -42,9 +42,9 @@ static volatile bool g_is_interrupted = false; static void show_additional_info(int /*argc*/, char ** argv) { LOG( - "Multimodal CLI with Spacemit EP vision engine\n\n" - "Usage: %s [options] -m --mmproj --image -p \n\n" - " -m and --mmproj are required (or set EP_CONFIG_DIR)\n" + "Multimodal CLI with Spacemit SMT vision backend\n\n" + "Usage: %s [options] -m --vision-backend smt --smt-config-dir

--image -p \n\n" + " -m and --smt-config-dir are required\n" " --image and -p are optional, if NOT provided, the CLI will run in chat mode\n", argv[0] ); @@ -124,7 +124,7 @@ static ep_image_boundary_mode ep_image_boundary_mode_from_env() { return ep_image_boundary_mode::none; } - LOG_WRN("[EP-v3] unknown MTMD_EP_IMAGE_BOUNDARY='%s', fallback to 'native'\n", env); + LOG_WRN("[SMT] unknown MTMD_EP_IMAGE_BOUNDARY='%s', fallback to 'native'\n", env); return ep_image_boundary_mode::native; } @@ -183,7 +183,7 @@ static ep_media_anchor_mode ep_media_anchor_mode_from_env() { if (value == "off" || value == "0" || value == "false") { return ep_media_anchor_mode::off; } - LOG_WRN("[EP-v3] unknown MTMD_EP_MEDIA_ANCHOR='%s', fallback to 'off'\n", env); + LOG_WRN("[SMT] unknown MTMD_EP_MEDIA_ANCHOR='%s', fallback to 'off'\n", env); return ep_media_anchor_mode::off; } @@ -733,23 +733,23 @@ struct mtmd_cli_ep_context { use_jinja = params.use_jinja; chat_history.clear(); - // Initialize EP vision context + // Initialize SMT vision context ep_ctx = ep_vision_context::create(ep_config_dir); hidden_size = ep_ctx->hidden_size(); use_mrope_pos = arch_requires_mrope(ep_ctx->architecture()); img_boundary_mode = ep_image_boundary_mode_from_env(); media_anchor_mode = ep_media_anchor_mode_from_env(); if (hidden_size <= 0 || hidden_size > INT_MAX) { - LOG_ERR("FATAL: invalid EP hidden_size (%" PRId64 ")\n", hidden_size); + LOG_ERR("FATAL: invalid SMT hidden_size (%" PRId64 ")\n", hidden_size); exit(1); } // Validate n_embd matches int model_n_embd = llama_model_n_embd(model); - LOG_INF("[EP-v3] EP vision engine initialized (hidden_size=%" PRId64 ", model_n_embd=%d, arch=%s)\n", + LOG_INF("[SMT] vision engine initialized (hidden_size=%" PRId64 ", model_n_embd=%d, arch=%s)\n", hidden_size, model_n_embd, ep_ctx->architecture().c_str()); if (model_n_embd != hidden_size) { - LOG_ERR("FATAL: model n_embd (%d) != EP hidden_size (%" PRId64 ")\n", model_n_embd, hidden_size); + LOG_ERR("FATAL: model n_embd (%d) != SMT hidden_size (%" PRId64 ")\n", model_n_embd, hidden_size); exit(1); } @@ -757,16 +757,16 @@ struct mtmd_cli_ep_context { auto boundaries = resolve_image_boundary_tokens(lctx, ep_ctx->architecture(), img_boundary_mode); tok_img_beg = std::move(boundaries.first); tok_img_end = std::move(boundaries.second); - LOG_INF("[EP-v3] image boundary mode: %s\n", ep_image_boundary_mode_name(img_boundary_mode)); - LOG_INF("[EP-v3] media anchor mode: %s\n", ep_media_anchor_mode_name(media_anchor_mode)); - LOG_INF("[EP-v3] mrope decode mode: %s\n", use_mrope_pos ? "enabled" : "disabled"); + LOG_INF("[SMT] image boundary mode: %s\n", ep_image_boundary_mode_name(img_boundary_mode)); + LOG_INF("[SMT] media anchor mode: %s\n", ep_media_anchor_mode_name(media_anchor_mode)); + LOG_INF("[SMT] mrope decode mode: %s\n", use_mrope_pos ? "enabled" : "disabled"); if (!tok_img_beg.empty() && !tok_img_end.empty() && tok_img_beg.front() != LLAMA_TOKEN_NULL && tok_img_end.front() != LLAMA_TOKEN_NULL) { - LOG_INF("[EP-v3] image boundary tokens enabled: beg='%s', end='%s'\n", + LOG_INF("[SMT] image boundary tokens enabled: beg='%s', end='%s'\n", common_token_to_piece(lctx, tok_img_beg.front()).c_str(), common_token_to_piece(lctx, tok_img_end.front()).c_str()); } else { - LOG_INF("[EP-v3] image boundary tokens disabled for this model (arch=%s)\n", + LOG_INF("[SMT] image boundary tokens disabled for this model (arch=%s)\n", ep_ctx->architecture().c_str()); tok_img_beg.clear(); tok_img_end.clear(); @@ -876,7 +876,7 @@ static int eval_message_ep(mtmd_cli_ep_context & ctx, common_chat_msg & msg) { ctx.media_anchor_mode, changed); if (changed) { - LOG_INF("[EP-v3] media-anchor canonicalization applied (%zu images)\n", ctx.pending_images.size()); + LOG_INF("[SMT] media-anchor canonicalization applied (%zu images)\n", ctx.pending_images.size()); } } @@ -901,7 +901,7 @@ static int eval_message_ep(mtmd_cli_ep_context & ctx, common_chat_msg & msg) { } // image chunk - LOG_INF("Encoding image chunk %zu with EP vision engine: %s\n", i, chunk.image_path.c_str()); + LOG_INF("Encoding image chunk %zu with SMT vision engine: %s\n", i, chunk.image_path.c_str()); std::string ep_input_path = chunk.image_path; std::string temp_input_path; try { @@ -910,7 +910,7 @@ static int eval_message_ep(mtmd_cli_ep_context & ctx, common_chat_msg & msg) { if (preproc.was_image) { temp_input_path = write_temp_bin_file(preproc.tensor_bytes); ep_input_path = temp_input_path; - LOG_INF("[EP-v3] preprocessed image '%s' -> [1,3,%d,%d] float32 (%s)\n", + LOG_INF("[SMT] preprocessed image '%s' -> [1,3,%d,%d] float32 (%s)\n", chunk.image_path.c_str(), preproc.target_h, preproc.target_w, @@ -936,7 +936,7 @@ static int eval_message_ep(mtmd_cli_ep_context & ctx, common_chat_msg & msg) { } if (image_embd.empty() || image_embd.size() % (size_t)ctx.hidden_size != 0) { - LOG_ERR("Invalid image embedding shape from EP (size=%zu, hidden_size=%" PRId64 ")\n", + LOG_ERR("Invalid image embedding shape from SMT (size=%zu, hidden_size=%" PRId64 ")\n", image_embd.size(), ctx.hidden_size); return 1; } @@ -948,7 +948,7 @@ static int eval_message_ep(mtmd_cli_ep_context & ctx, common_chat_msg & msg) { auto grid_xy = infer_image_grid_xy(n_image_tokens); grid_nx = grid_xy.first; grid_ny = grid_xy.second; - LOG_INF("[EP-v3] inferred image token grid: nx=%d, ny=%d, n_tokens=%d\n", + LOG_INF("[SMT] inferred image token grid: nx=%d, ny=%d, n_tokens=%d\n", grid_nx, grid_ny, n_image_tokens); } @@ -985,34 +985,19 @@ static int eval_message_ep(mtmd_cli_ep_context & ctx, common_chat_msg & msg) { // Main function // ============================================================ -int main(int argc, char ** argv) { +int mtmd_cli_smt_run(int argc, char ** argv, common_params params) { ggml_time_init(); - LOG_INF("MTMD_CLI_EP_BUILD_TAG: fastvlm-support-20260303-3 (%s %s)\n", __DATE__, __TIME__); - - common_params params; - - if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_MTMD, show_additional_info)) { - return 1; - } + LOG_INF("MTMD_CLI_SMT_BUILD_TAG: spacemit-smt (%s %s)\n", __DATE__, __TIME__); common_init(); - // Use --mmproj as EP config directory path - std::string ep_config_dir = params.mmproj.path; - if (ep_config_dir.empty()) { - // Fallback: check environment variable - const char * env = std::getenv("EP_CONFIG_DIR"); - if (env) { - ep_config_dir = env; - } - } - if (ep_config_dir.empty()) { + if (params.smt_config_dir.empty()) { show_additional_info(argc, argv); - LOG_ERR("ERR: Missing EP config directory (pass via --mmproj or EP_CONFIG_DIR env)\n"); + LOG_ERR("ERR: Missing --smt-config-dir argument\n"); return 1; } - mtmd_cli_ep_context ctx(params, ep_config_dir); + mtmd_cli_ep_context ctx(params, params.smt_config_dir); bool is_single_turn = !params.prompt.empty() && !params.image.empty(); int n_predict = params.n_predict < 0 ? INT_MAX : params.n_predict; @@ -1046,7 +1031,7 @@ int main(int argc, char ** argv) { return eval_message_ep(ctx, msg); }; - LOG_WRN("Multimodal CLI with Spacemit EP vision engine\n"); + LOG_WRN("Multimodal CLI with Spacemit SMT vision backend\n"); if (eval_system_prompt_if_present()) { return 1; @@ -1078,7 +1063,7 @@ int main(int argc, char ** argv) { } } else { // Chat mode - LOG("\n Running in chat mode (EP vision), available commands:"); + LOG("\n Running in chat mode (SMT vision), available commands:"); LOG("\n /image load an image (.jpg/.png/...) or preprocessed .bin"); LOG("\n /clear clear the chat history"); LOG("\n /quit or /exit exit the program"); diff --git a/tools/mtmd/mtmd-cli.cpp b/tools/mtmd/mtmd-cli.cpp index d6e551618e88..910276a423e9 100644 --- a/tools/mtmd/mtmd-cli.cpp +++ b/tools/mtmd/mtmd-cli.cpp @@ -38,6 +38,19 @@ static volatile bool g_is_interrupted = false; */ static void show_additional_info(int /*argc*/, char ** argv) { +#if defined(LLAMA_SERVER_SMT_VISION) + LOG( + "Experimental CLI for multimodal\n\n" + "Usage: %s [options] -m [--mmproj | --smt-config-dir ] --image --audio