mtmd.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954
  1. #include "clip.h"
  2. #include "clip-impl.h"
  3. #include "mtmd.h"
  4. #include "mtmd-audio.h"
  5. #include "llama.h"
  6. #include <algorithm>
  7. #include <cerrno>
  8. #include <cstdio>
  9. #include <cstdlib>
  10. #include <cstring>
  11. #include <limits>
  12. #include <vector>
  13. // represents raw image data, layout is RGBRGBRGB...
  14. // length of data must be nx * ny * 3
  15. struct mtmd_bitmap {
  16. uint32_t nx;
  17. uint32_t ny;
  18. std::vector<unsigned char> data;
  19. std::string id; // optional user-defined id, for ex: can be set to image hash, useful for KV cache tracking
  20. bool is_audio = false; // true if the bitmap is audio
  21. };
  22. struct mtmd_image_tokens {
  23. uint32_t nx; // number of tokens in x direction
  24. uint32_t ny; // number of tokens in y direction
  25. bool use_mrope_pos = false; // use M-RoPE position counting (the whole image is 1 temporal position)
  26. uint32_t n_tokens() const { return nx * ny; }
  27. clip_image_f32_batch batch_f32; // preprocessed image patches
  28. std::string id; // optional user-defined ID, useful for KV cache tracking
  29. mtmd_image_tokens clone() {
  30. return mtmd_image_tokens{
  31. nx,
  32. ny,
  33. use_mrope_pos,
  34. batch_f32.clone(),
  35. id
  36. };
  37. }
  38. };
  39. using mtmd_image_tokens_ptr = std::unique_ptr<mtmd_image_tokens>;
  40. struct mtmd_audio_tokens {
  41. uint32_t n_tokens; // number of tokens
  42. clip_image_f32_batch batch_f32; // preprocessed image patches
  43. std::string id; // optional user-defined ID, useful for KV cache tracking
  44. mtmd_audio_tokens clone() {
  45. return mtmd_audio_tokens{
  46. n_tokens,
  47. batch_f32.clone(),
  48. id
  49. };
  50. }
  51. };
  52. using mtmd_audio_tokens_ptr = std::unique_ptr<mtmd_audio_tokens>;
  53. struct mtmd_input_chunk {
  54. mtmd_input_chunk_type type;
  55. std::vector<llama_token> tokens_text;
  56. mtmd_image_tokens_ptr tokens_image;
  57. mtmd_audio_tokens_ptr tokens_audio;
  58. };
  59. struct mtmd_input_chunks {
  60. std::vector<mtmd_input_chunk> entries;
  61. };
  62. // slice template, used by some llava-uhd models to correctly place the special tokens around image embeddings
  63. // models not having it (llava-1.6) will process embeddings without any special tokens in-between
  64. enum mtmd_slice_tmpl {
  65. MTMD_SLICE_TMPL_NONE,
  66. MTMD_SLICE_TMPL_MINICPMV_2_5,
  67. MTMD_SLICE_TMPL_MINICPMV_2_6,
  68. MTMD_SLICE_TMPL_LLAMA4,
  69. // TODO @ngxson : add support for idefics (SmolVLM)
  70. };
  71. const char * mtmd_default_marker() {
  72. return "<__media__>";
  73. }
  74. mtmd_context_params mtmd_context_params_default() {
  75. mtmd_context_params params;
  76. params.use_gpu = true;
  77. params.print_timings = true;
  78. params.n_threads = 4;
  79. params.verbosity = GGML_LOG_LEVEL_INFO;
  80. params.image_marker = MTMD_DEFAULT_IMAGE_MARKER;
  81. params.media_marker = mtmd_default_marker();
  82. return params;
  83. }
  84. struct mtmd_context {
  85. struct clip_ctx * ctx_clip;
  86. const struct llama_model * text_model;
  87. std::vector<float> image_embd_v; // image embedding vector
  88. bool print_timings;
  89. int n_threads;
  90. std::string media_marker;
  91. bool has_vision;
  92. bool has_audio;
  93. // for llava-uhd style models, we need special tokens in-between slices
  94. // minicpmv calls them "slices", llama 4 calls them "tiles"
  95. mtmd_slice_tmpl slice_tmpl = MTMD_SLICE_TMPL_NONE;
  96. llama_token tok_ov_img_start = LLAMA_TOKEN_NULL; // overview image
  97. llama_token tok_ov_img_end = LLAMA_TOKEN_NULL; // overview image
  98. llama_token tok_slices_start = LLAMA_TOKEN_NULL; // start of all slices
  99. llama_token tok_slices_end = LLAMA_TOKEN_NULL; // end of all slices
  100. llama_token tok_sli_img_start = LLAMA_TOKEN_NULL; // single slice start
  101. llama_token tok_sli_img_end = LLAMA_TOKEN_NULL; // single slice end
  102. llama_token tok_sli_img_mid = LLAMA_TOKEN_NULL; // between 2 slices
  103. llama_token tok_row_end = LLAMA_TOKEN_NULL; // end of row
  104. bool tok_row_end_trail = false;
  105. bool ov_img_first = false;
  106. bool use_mrope = false; // for Qwen2VL, we need to use M-RoPE
  107. // for whisper, we pre-calculate the mel filter bank
  108. whisper_preprocessor::whisper_filters w_filters;
  109. // TODO @ngxson : add timings
  110. mtmd_context(const char * mmproj_fname,
  111. const llama_model * text_model,
  112. const mtmd_context_params & ctx_params) :
  113. text_model (text_model),
  114. print_timings(ctx_params.print_timings),
  115. n_threads (ctx_params.n_threads),
  116. media_marker (ctx_params.media_marker)
  117. {
  118. if (std::string(ctx_params.image_marker) != MTMD_DEFAULT_IMAGE_MARKER) {
  119. throw std::runtime_error("custom image_marker is not supported anymore, use media_marker instead");
  120. }
  121. clip_context_params ctx_clip_params;
  122. ctx_clip_params.use_gpu = ctx_params.use_gpu;
  123. ctx_clip_params.verbosity = ctx_params.verbosity;
  124. ctx_clip = clip_init(mmproj_fname, ctx_clip_params);
  125. if (!ctx_clip) {
  126. throw std::runtime_error(string_format("Failed to load CLIP model from %s\n", mmproj_fname));
  127. }
  128. if (llama_model_n_embd(text_model) != clip_n_mmproj_embd(ctx_clip)) {
  129. throw std::runtime_error(string_format(
  130. "mismatch between text model (n_embd = %d) and mmproj (n_embd = %d)\n"
  131. "hint: you may be using wrong mmproj\n",
  132. llama_model_n_embd(text_model), clip_n_mmproj_embd(ctx_clip)));
  133. }
  134. has_vision = clip_has_vision_encoder(ctx_clip);
  135. has_audio = clip_has_audio_encoder(ctx_clip);
  136. use_mrope = clip_is_qwen2vl(ctx_clip);
  137. projector_type proj = clip_get_projector_type(ctx_clip);
  138. int minicpmv_version = clip_is_minicpmv(ctx_clip);
  139. if (minicpmv_version == 2) {
  140. // minicpmv 2.5 format:
  141. // <image> (overview) </image><slice><image> (slice) </image><image> (slice) </image>\n ... </slice>
  142. slice_tmpl = MTMD_SLICE_TMPL_MINICPMV_2_5;
  143. tok_ov_img_start = lookup_token("<image>");
  144. tok_ov_img_end = lookup_token("</image>");
  145. tok_slices_start = lookup_token("<slice>");
  146. tok_slices_end = lookup_token("</slice>");
  147. tok_sli_img_start = tok_ov_img_start;
  148. tok_sli_img_end = tok_ov_img_end;
  149. tok_row_end = lookup_token("\n");
  150. tok_row_end_trail = false; // no trailing end-of-row token
  151. ov_img_first = true;
  152. } else if (minicpmv_version == 3 || minicpmv_version == 4) {
  153. // minicpmv 2.6 format:
  154. // <image> (overview) </image><slice> (slice) </slice><slice> (slice) </slice>\n ...
  155. slice_tmpl = MTMD_SLICE_TMPL_MINICPMV_2_6;
  156. tok_ov_img_start = lookup_token("<image>");
  157. tok_ov_img_end = lookup_token("</image>");
  158. tok_sli_img_start = lookup_token("<slice>");
  159. tok_sli_img_end = lookup_token("</slice>");
  160. tok_row_end = lookup_token("\n");
  161. tok_row_end_trail = false; // no trailing end-of-row token
  162. ov_img_first = true;
  163. } else if (minicpmv_version != 0) {
  164. GGML_ASSERT(false && "unsupported minicpmv version");
  165. } else if (proj == PROJECTOR_TYPE_LLAMA4) {
  166. // llama 4 format:
  167. // <|image_start|>
  168. // (slice) <|tile_x_separator|> (slice) <|tile_x_separator|> ... <|tile_y_separator|>
  169. // (slice) <|tile_x_separator|> (slice) <|tile_x_separator|> ... <|tile_y_separator|>
  170. // ... <|tile_y_separator|> <-- trailing end-of-row token
  171. // <|image|> (overview) <-- overview image is last
  172. // <|image_end|>
  173. slice_tmpl = MTMD_SLICE_TMPL_LLAMA4;
  174. tok_ov_img_start = lookup_token("<|image|>");
  175. tok_sli_img_mid = lookup_token("<|tile_x_separator|>");
  176. tok_row_end = lookup_token("<|tile_y_separator|>");
  177. tok_row_end_trail = true; // add trailing end-of-row token
  178. ov_img_first = false; // overview image is last
  179. }
  180. if (clip_has_whisper_encoder(ctx_clip)) {
  181. // TODO @ngxson : check if model n_mel is 128 or 80
  182. w_filters = whisper_precalc_filters::get_128_bins();
  183. }
  184. // warning messages
  185. if (proj == PROJECTOR_TYPE_LLAMA4) {
  186. LOG_WRN("%s: llama 4 vision is known to have degraded quality:\n"
  187. " https://github.com/ggml-org/llama.cpp/pull/13282\n", __func__);
  188. }
  189. if (has_audio) {
  190. LOG_WRN("%s: audio input is in experimental stage and may have reduced quality:\n"
  191. " https://github.com/ggml-org/llama.cpp/discussions/13759\n", __func__);
  192. }
  193. }
  194. ~mtmd_context() {
  195. clip_free(ctx_clip);
  196. }
  197. private:
  198. llama_token lookup_token(const std::string & token_text) {
  199. const llama_vocab * vocab = llama_model_get_vocab(text_model);
  200. const int n_vocab = llama_vocab_n_tokens(vocab);
  201. for (int i = 0; i < n_vocab; i++) {
  202. if (token_to_piece(vocab, i, true) == token_text) {
  203. return i;
  204. }
  205. }
  206. return LLAMA_TOKEN_NULL;
  207. }
  208. std::string token_to_piece(const llama_vocab * vocab, llama_token token, bool special) {
  209. std::string piece;
  210. piece.resize(piece.capacity()); // using string internal cache, 15 bytes + '\n'
  211. const int n_chars = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
  212. if (n_chars < 0) {
  213. piece.resize(-n_chars);
  214. int check = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
  215. GGML_ASSERT(check == -n_chars);
  216. } else {
  217. piece.resize(n_chars);
  218. }
  219. return piece;
  220. }
  221. };
  222. mtmd_context * mtmd_init_from_file(const char * mmproj_fname,
  223. const struct llama_model * text_model,
  224. const struct mtmd_context_params ctx_params) {
  225. try {
  226. return new mtmd_context(mmproj_fname, text_model, ctx_params);
  227. } catch (const std::exception & e) {
  228. LOG_ERR("%s: error: %s\n", __func__, e.what());
  229. return nullptr;
  230. }
  231. }
  232. void mtmd_free(mtmd_context * ctx) {
  233. if (ctx) {
  234. delete ctx;
  235. }
  236. }
  237. // copied from common_tokenize
  238. static std::vector<llama_token> mtmd_tokenize_text_internal(
  239. const struct llama_vocab * vocab,
  240. const std::string & text,
  241. bool add_special,
  242. bool parse_special) {
  243. // upper limit for the number of tokens
  244. int n_tokens = text.length() + 2 * add_special;
  245. std::vector<llama_token> result(n_tokens);
  246. n_tokens = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  247. if (n_tokens < 0) {
  248. result.resize(-n_tokens);
  249. int check = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  250. GGML_ASSERT(check == -n_tokens);
  251. } else {
  252. result.resize(n_tokens);
  253. }
  254. return result;
  255. }
  256. int32_t mtmd_tokenize(mtmd_context * ctx,
  257. mtmd_input_chunks * output,
  258. const mtmd_input_text * text,
  259. const mtmd_bitmap ** bitmaps,
  260. size_t n_bitmaps) {
  261. auto vocab = llama_model_get_vocab(ctx->text_model);
  262. std::string prompt_modified(text->text);
  263. std::string marker_modified(ctx->media_marker);
  264. projector_type proj_type = clip_get_projector_type(ctx->ctx_clip);
  265. // for compatibility, we convert image marker to media marker
  266. string_replace_all(prompt_modified, MTMD_DEFAULT_IMAGE_MARKER, ctx->media_marker);
  267. // a bit hacky here, but works for now
  268. // for some models, we need to add prefix and suffix to the image embeddings
  269. if (clip_is_gemma3(ctx->ctx_clip)) {
  270. // gemma 3
  271. // <start_of_image> ... (image embeddings) ... <end_of_image>
  272. marker_modified = "<start_of_image>" + ctx->media_marker + "<end_of_image>";
  273. string_replace_all(prompt_modified, ctx->media_marker, marker_modified);
  274. } else if (proj_type == PROJECTOR_TYPE_IDEFICS3) {
  275. // https://github.com/huggingface/transformers/blob/a42ba80fa520c784c8f11a973ca9034e5f859b79/src/transformers/models/idefics3/processing_idefics3.py#L192-L215
  276. marker_modified = "<fake_token_around_image><global-img>" + ctx->media_marker + "<fake_token_around_image>";
  277. string_replace_all(prompt_modified, ctx->media_marker, marker_modified);
  278. } else if (proj_type == PROJECTOR_TYPE_PIXTRAL) {
  279. // https://github.com/huggingface/transformers/blob/1cd110c6cb6a6237614130c470e9a902dbc1a4bd/docs/source/en/model_doc/pixtral.md
  280. marker_modified = ctx->media_marker + "[IMG_END]";
  281. string_replace_all(prompt_modified, ctx->media_marker, marker_modified);
  282. } else if (proj_type == PROJECTOR_TYPE_QWEN2VL || proj_type == PROJECTOR_TYPE_QWEN25VL) {
  283. // <|vision_start|> ... (image embeddings) ... <|vision_end|>
  284. marker_modified = "<|vision_start|>" + ctx->media_marker + "<|vision_end|>";
  285. string_replace_all(prompt_modified, ctx->media_marker, marker_modified);
  286. } else if (proj_type == PROJECTOR_TYPE_LLAMA4) {
  287. // (more details in mtmd_context constructor)
  288. marker_modified = "<|image_start|>" + ctx->media_marker + "<|image_end|>";
  289. string_replace_all(prompt_modified, ctx->media_marker, marker_modified);
  290. } else if (proj_type == PROJECTOR_TYPE_INTERNVL) {
  291. // <img> ... (image embeddings) ... </img>
  292. marker_modified = "<img>" + ctx->media_marker + "</img>";
  293. string_replace_all(prompt_modified, ctx->media_marker, marker_modified);
  294. } else if (proj_type == PROJECTOR_TYPE_QWEN2A) {
  295. // <|audio_bos|> ... (embeddings) ... <|audio_eos|>
  296. marker_modified = "<|audio_bos|>" + ctx->media_marker + "<|audio_eos|>";
  297. string_replace_all(prompt_modified, ctx->media_marker, marker_modified);
  298. }
  299. // llava-1.5, llava-1.6, Yi-VL, Yi-34B, granite: don't need to add prefix and suffix
  300. // for glm-edge, BOI and EOI token's embeddings are not present in the text model
  301. std::vector<std::string> parts = string_split_str(prompt_modified, ctx->media_marker);
  302. output->entries.clear();
  303. output->entries.reserve(parts.size());
  304. size_t i_bm = 0;
  305. // utility for adding raw tokens
  306. auto add_text_chunk = [&output](std::vector<llama_token> && tokens) {
  307. mtmd_input_chunk chunk{
  308. MTMD_INPUT_CHUNK_TYPE_TEXT,
  309. std::move(tokens),
  310. nullptr, // image tokens
  311. nullptr, // audio tokens
  312. };
  313. output->entries.emplace_back(std::move(chunk));
  314. };
  315. // utility for splitting batch of multiple images into chunks of batch having single images
  316. auto split_batch_to_chunk = [&ctx](clip_image_f32_batch && batch_f32, const std::string & id) {
  317. std::vector<mtmd_input_chunk> chunks;
  318. for (auto & entry : batch_f32.entries) {
  319. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  320. image_tokens->nx = clip_n_output_tokens(ctx->ctx_clip, entry.get());
  321. image_tokens->ny = 1;
  322. image_tokens->batch_f32.entries.push_back(std::move(entry));
  323. image_tokens->id = id;
  324. mtmd_input_chunk chunk{
  325. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  326. {}, // text tokens
  327. std::move(image_tokens),
  328. nullptr, // audio tokens
  329. };
  330. chunks.emplace_back(std::move(chunk));
  331. }
  332. return chunks;
  333. };
  334. for (const auto & part : parts) {
  335. // printf("tokenizing part: %s\n", part.c_str());
  336. bool add_bos = &parts.front() == &part;
  337. auto tokens = mtmd_tokenize_text_internal(vocab, part, text->add_special && add_bos, text->parse_special);
  338. if (tokens.empty()) {
  339. continue;
  340. }
  341. mtmd_input_chunk chunk{
  342. MTMD_INPUT_CHUNK_TYPE_TEXT,
  343. std::move(tokens),
  344. nullptr, // image tokens
  345. nullptr, // audio tokens
  346. };
  347. output->entries.emplace_back(std::move(chunk));
  348. // only add image/audio tokens to middle of 2 parts
  349. // therefore, we skip handling image/audio if this is the last part
  350. if (&parts.back() == &part) {
  351. continue;
  352. }
  353. if (!bitmaps[i_bm]->is_audio) {
  354. // handle image
  355. if (i_bm >= n_bitmaps) {
  356. LOG_ERR("%s: error: not enough images for %d parts\n", __func__, (int)parts.size());
  357. return 1;
  358. }
  359. if (!ctx->has_vision) {
  360. LOG_ERR("%s: error: model does not support vision input\n", __func__);
  361. return 2;
  362. }
  363. // convert mtmd_bitmap to clip_image_u8
  364. clip_image_u8_ptr img_u8(clip_image_u8_init());
  365. img_u8->nx = bitmaps[i_bm]->nx;
  366. img_u8->ny = bitmaps[i_bm]->ny;
  367. img_u8->buf.resize(bitmaps[i_bm]->data.size());
  368. std::memcpy(img_u8->buf.data(), bitmaps[i_bm]->data.data(), img_u8->nx * img_u8->ny * 3);
  369. // preprocess image
  370. clip_image_f32_batch batch_f32;
  371. bool ok = clip_image_preprocess(ctx->ctx_clip, img_u8.get(), &batch_f32);
  372. if (!ok) {
  373. LOG_ERR("Unable to preprocess image\n");
  374. return 2;
  375. }
  376. // handle llava-uhd style preprocessing
  377. if (
  378. ctx->slice_tmpl == MTMD_SLICE_TMPL_MINICPMV_2_5
  379. || ctx->slice_tmpl == MTMD_SLICE_TMPL_MINICPMV_2_6
  380. || ctx->slice_tmpl == MTMD_SLICE_TMPL_LLAMA4
  381. ) {
  382. // split batch into chunks of single images
  383. auto chunks = split_batch_to_chunk(std::move(batch_f32), bitmaps[i_bm]->id);
  384. GGML_ASSERT(chunks.size() > 0);
  385. auto ov_chunk = std::move(chunks.front());
  386. chunks.erase(chunks.begin());
  387. // add overview image (first)
  388. if (ctx->ov_img_first) {
  389. if (ctx->tok_ov_img_start != LLAMA_TOKEN_NULL) {
  390. add_text_chunk({ctx->tok_ov_img_start});
  391. }
  392. output->entries.emplace_back(std::move(ov_chunk));
  393. if (ctx->tok_ov_img_end != LLAMA_TOKEN_NULL) {
  394. add_text_chunk({ctx->tok_ov_img_end});
  395. }
  396. }
  397. // add slices (or tiles)
  398. if (!chunks.empty()) {
  399. const int n_col = batch_f32.grid_x;
  400. const int n_row = batch_f32.grid_y;
  401. if (ctx->tok_slices_start != LLAMA_TOKEN_NULL) {
  402. add_text_chunk({ctx->tok_slices_start});
  403. }
  404. for (int y = 0; y < n_row; y++) {
  405. for (int x = 0; x < n_col; x++) {
  406. const bool is_last_in_row = (x == n_col - 1);
  407. if (ctx->tok_sli_img_start != LLAMA_TOKEN_NULL) {
  408. add_text_chunk({ctx->tok_sli_img_start});
  409. }
  410. output->entries.emplace_back(std::move(chunks[y * n_col + x]));
  411. if (ctx->tok_sli_img_end != LLAMA_TOKEN_NULL) {
  412. add_text_chunk({ctx->tok_sli_img_end});
  413. }
  414. if (!is_last_in_row && ctx->tok_sli_img_mid != LLAMA_TOKEN_NULL) {
  415. add_text_chunk({ctx->tok_sli_img_mid});
  416. }
  417. }
  418. if ((y != n_row - 1 || ctx->tok_row_end_trail) && ctx->tok_row_end != LLAMA_TOKEN_NULL) {
  419. add_text_chunk({ctx->tok_row_end});
  420. }
  421. }
  422. if (ctx->tok_slices_end != LLAMA_TOKEN_NULL) {
  423. add_text_chunk({ctx->tok_slices_end});
  424. }
  425. }
  426. // add overview image (last)
  427. if (!ctx->ov_img_first) {
  428. if (ctx->tok_ov_img_start != LLAMA_TOKEN_NULL) {
  429. add_text_chunk({ctx->tok_ov_img_start});
  430. }
  431. output->entries.emplace_back(std::move(ov_chunk));
  432. if (ctx->tok_ov_img_end != LLAMA_TOKEN_NULL) {
  433. add_text_chunk({ctx->tok_ov_img_end});
  434. }
  435. }
  436. } else {
  437. size_t n_tokens = 0;
  438. for (const auto & entry : batch_f32.entries) {
  439. n_tokens += clip_n_output_tokens(ctx->ctx_clip, entry.get());
  440. }
  441. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  442. if (ctx->use_mrope) {
  443. // for Qwen2VL, we need this information for M-RoPE decoding positions
  444. image_tokens->nx = clip_n_output_tokens_x(ctx->ctx_clip, batch_f32.entries[0].get());
  445. image_tokens->ny = clip_n_output_tokens_y(ctx->ctx_clip, batch_f32.entries[0].get());
  446. image_tokens->use_mrope_pos = true;
  447. } else {
  448. // other models, we only need the total number of tokens
  449. image_tokens->nx = n_tokens;
  450. image_tokens->ny = 1;
  451. }
  452. image_tokens->batch_f32 = std::move(batch_f32);
  453. image_tokens->id = bitmaps[i_bm]->id; // optional
  454. LOG_DBG("image_tokens->nx = %d\n", image_tokens->nx);
  455. LOG_DBG("image_tokens->ny = %d\n", image_tokens->ny);
  456. LOG_DBG("batch_f32 size = %d\n", (int)image_tokens->batch_f32.entries.size());
  457. mtmd_input_chunk chunk{
  458. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  459. {}, // text tokens
  460. std::move(image_tokens),
  461. nullptr, // audio tokens
  462. };
  463. output->entries.emplace_back(std::move(chunk));
  464. }
  465. i_bm++; // move to next image
  466. continue;
  467. } else {
  468. // handle audio
  469. if (i_bm >= n_bitmaps) {
  470. LOG_ERR("%s: error: not enough images for %d parts\n", __func__, (int)parts.size());
  471. return 1;
  472. }
  473. if (!ctx->has_audio) {
  474. LOG_ERR("%s: error: model does not support audio input\n", __func__);
  475. return 2;
  476. }
  477. if (bitmaps[i_bm]->data.size() == 0) {
  478. LOG_ERR("%s: error: empty audio data\n", __func__);
  479. return 2;
  480. }
  481. // preprocess audio
  482. GGML_ASSERT(ctx->w_filters.n_mel); // make sure we have filter preloaded
  483. std::vector<whisper_preprocessor::whisper_mel> mel_spec_chunks;
  484. const float * samples = (const float *)bitmaps[i_bm]->data.data();
  485. size_t n_samples = bitmaps[i_bm]->data.size() / sizeof(float);
  486. bool ok = whisper_preprocessor::preprocess_audio(samples, n_samples, ctx->w_filters, mel_spec_chunks);
  487. if (!ok) {
  488. LOG_ERR("Unable to preprocess audio\n");
  489. return 2;
  490. }
  491. // consider each mel_spec as a separate audio chunk
  492. // TODO: maybe support batching, but this may come with memory cost
  493. for (auto & mel_spec : mel_spec_chunks) {
  494. clip_image_f32_ptr mel_f32(clip_image_f32_init());
  495. mel_f32->nx = mel_spec.n_len;
  496. mel_f32->ny = mel_spec.n_mel;
  497. mel_f32->buf = std::move(mel_spec.data);
  498. size_t n_tokens = clip_n_output_tokens(ctx->ctx_clip, mel_f32.get());
  499. clip_image_f32_batch batch_f32;
  500. batch_f32.is_audio = true;
  501. batch_f32.entries.push_back(std::move(mel_f32));
  502. mtmd_audio_tokens_ptr audio_tokens(new mtmd_audio_tokens);
  503. audio_tokens->n_tokens = n_tokens;
  504. audio_tokens->batch_f32 = std::move(batch_f32);
  505. audio_tokens->id = bitmaps[i_bm]->id; // optional
  506. LOG_DBG("audio_tokens->n_tokens = %d\n", audio_tokens->n_tokens);
  507. mtmd_input_chunk chunk{
  508. MTMD_INPUT_CHUNK_TYPE_AUDIO,
  509. {}, // text tokens
  510. nullptr, // image tokens
  511. std::move(audio_tokens),
  512. };
  513. output->entries.emplace_back(std::move(chunk));
  514. }
  515. i_bm++;
  516. continue;
  517. }
  518. }
  519. return 0;
  520. }
  521. int32_t mtmd_encode_chunk(mtmd_context * ctx, const mtmd_input_chunk * chunk) {
  522. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  523. LOG_WRN("mtmd_encode_chunk has no effect for text chunks\n");
  524. return 0;
  525. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  526. return mtmd_encode(ctx, chunk->tokens_image.get());
  527. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
  528. int n_mmproj_embd = clip_n_mmproj_embd(ctx->ctx_clip);
  529. ctx->image_embd_v.resize(chunk->tokens_audio->n_tokens * n_mmproj_embd);
  530. bool ok = clip_image_batch_encode(
  531. ctx->ctx_clip,
  532. ctx->n_threads,
  533. &chunk->tokens_audio->batch_f32,
  534. ctx->image_embd_v.data());
  535. return ok ? 0 : 1;
  536. }
  537. LOG_ERR("mtmd_encode_chunk: unknown chunk type %d\n", (int)chunk->type);
  538. return 1;
  539. }
  540. int32_t mtmd_encode(mtmd_context * ctx, const mtmd_image_tokens * image_tokens) {
  541. int n_mmproj_embd = clip_n_mmproj_embd(ctx->ctx_clip);
  542. ctx->image_embd_v.resize(image_tokens->n_tokens() * n_mmproj_embd);
  543. bool ok = false;
  544. if (clip_is_llava(ctx->ctx_clip) || clip_is_minicpmv(ctx->ctx_clip) || clip_is_glm(ctx->ctx_clip)) {
  545. // TODO @ngxson : llava does not support batched encoding ; this should be fixed inside clip_image_batch_encode()
  546. const auto & entries = image_tokens->batch_f32.entries;
  547. for (size_t i = 0; i < entries.size(); i++) {
  548. int n_tokens_per_image = clip_n_output_tokens(ctx->ctx_clip, entries[i].get());
  549. ok = clip_image_encode(
  550. ctx->ctx_clip,
  551. ctx->n_threads,
  552. entries[i].get(),
  553. ctx->image_embd_v.data() + i*n_mmproj_embd*n_tokens_per_image);
  554. }
  555. } else {
  556. ok = clip_image_batch_encode(
  557. ctx->ctx_clip,
  558. ctx->n_threads,
  559. &image_tokens->batch_f32,
  560. ctx->image_embd_v.data());
  561. }
  562. return ok ? 0 : 1;
  563. }
  564. float * mtmd_get_output_embd(mtmd_context * ctx) {
  565. return ctx->image_embd_v.data();
  566. }
  567. bool mtmd_decode_use_non_causal(mtmd_context * ctx) {
  568. projector_type proj_type = clip_get_projector_type(ctx->ctx_clip);
  569. if (proj_type == PROJECTOR_TYPE_GEMMA3) {
  570. return true;
  571. }
  572. return false;
  573. }
  574. bool mtmd_decode_use_mrope(mtmd_context * ctx) {
  575. return ctx->use_mrope;
  576. }
  577. bool mtmd_support_vision(mtmd_context * ctx) {
  578. return ctx->has_vision;
  579. }
  580. bool mtmd_support_audio(mtmd_context * ctx) {
  581. return ctx->has_audio;
  582. }
  583. // these 2 helpers below use internal clip_image_u8_ptr,
  584. // so unfortunately they cannot moved to mtmd-helper.h
  585. // however, in theory, user can decode image file to bitmap using
  586. // whichever library they want, and then use mtmd_bitmap_init() to create bitmap
  587. mtmd_bitmap * mtmd_helper_bitmap_init_from_buf(const unsigned char * buf, size_t len) {
  588. if (audio_helpers::is_audio_file((const char *)buf, len)) {
  589. std::vector<float> pcmf32;
  590. if (!audio_helpers::decode_audio_from_buf(buf, len, COMMON_SAMPLE_RATE, pcmf32)) {
  591. LOG_ERR("Unable to read WAV audio file from buffer\n");
  592. return nullptr;
  593. }
  594. return mtmd_bitmap_init_from_audio(pcmf32.size(), pcmf32.data());
  595. }
  596. clip_image_u8_ptr img_u8(clip_image_u8_init());
  597. bool ok = clip_image_load_from_bytes(buf, len, img_u8.get());
  598. if (!ok) {
  599. LOG_ERR("Unable to load image from buffer\n");
  600. return nullptr;
  601. }
  602. uint32_t nx, ny;
  603. unsigned char * data = clip_image_u8_get_data(img_u8.get(), &nx, &ny);
  604. return mtmd_bitmap_init(nx, ny, data);
  605. }
  606. mtmd_bitmap * mtmd_helper_bitmap_init_from_file(const char * fname) {
  607. std::vector<unsigned char> buf;
  608. FILE * f = fopen(fname, "rb");
  609. if (!f) {
  610. LOG_ERR("Unable to open file %s: %s\n", fname, strerror(errno));
  611. return nullptr;
  612. }
  613. fseek(f, 0, SEEK_END);
  614. long file_size = ftell(f);
  615. fseek(f, 0, SEEK_SET);
  616. buf.resize(file_size);
  617. size_t n_read = fread(buf.data(), 1, file_size, f);
  618. fclose(f);
  619. if (n_read != (size_t)file_size) {
  620. LOG_ERR("Failed to read entire file %s", fname);
  621. return nullptr;
  622. }
  623. return mtmd_helper_bitmap_init_from_buf(buf.data(), buf.size());
  624. }
  625. //
  626. // public API functions
  627. //
  628. // mtmd_bitmap
  629. mtmd_bitmap * mtmd_bitmap_init(uint32_t nx,
  630. uint32_t ny,
  631. const unsigned char * data) {
  632. mtmd_bitmap * bitmap = new mtmd_bitmap;
  633. bitmap->nx = nx;
  634. bitmap->ny = ny;
  635. size_t data_size = (size_t)nx * ny * 3;
  636. bitmap->data.resize(data_size);
  637. std::memcpy(bitmap->data.data(), data, data_size);
  638. return bitmap;
  639. }
  640. mtmd_bitmap * mtmd_bitmap_init_from_audio(size_t n_samples,
  641. const float * data) {
  642. mtmd_bitmap * bitmap = new mtmd_bitmap;
  643. bitmap->nx = n_samples;
  644. bitmap->ny = 1;
  645. bitmap->is_audio = true;
  646. size_t data_size = n_samples * sizeof(float);
  647. bitmap->data.resize(data_size);
  648. std::memcpy(bitmap->data.data(), data, data_size);
  649. return bitmap;
  650. }
  651. uint32_t mtmd_bitmap_get_nx(const mtmd_bitmap * bitmap) {
  652. return bitmap->nx;
  653. }
  654. uint32_t mtmd_bitmap_get_ny(const mtmd_bitmap * bitmap) {
  655. return bitmap->ny;
  656. }
  657. const unsigned char * mtmd_bitmap_get_data(const mtmd_bitmap * bitmap) {
  658. return bitmap->data.data();
  659. }
  660. size_t mtmd_bitmap_get_n_bytes(const mtmd_bitmap * bitmap) {
  661. return bitmap->data.size();
  662. }
  663. bool mtmd_bitmap_is_audio(const mtmd_bitmap * bitmap) {
  664. return bitmap->is_audio;
  665. }
  666. const char * mtmd_bitmap_get_id(const mtmd_bitmap * bitmap) {
  667. return bitmap->id.c_str();
  668. }
  669. void mtmd_bitmap_set_id(mtmd_bitmap * bitmap, const char * id) {
  670. if (id) {
  671. bitmap->id = std::string(id);
  672. } else {
  673. bitmap->id.clear();
  674. }
  675. }
  676. void mtmd_bitmap_free(mtmd_bitmap * bitmap) {
  677. if (bitmap) {
  678. delete bitmap;
  679. }
  680. }
  681. // mtmd_input_chunks
  682. mtmd_input_chunks * mtmd_input_chunks_init() {
  683. return new mtmd_input_chunks;
  684. }
  685. size_t mtmd_input_chunks_size(const mtmd_input_chunks * chunks) {
  686. return chunks->entries.size();
  687. }
  688. const mtmd_input_chunk * mtmd_input_chunks_get(const mtmd_input_chunks * chunks, size_t idx) {
  689. if (idx >= chunks->entries.size()) {
  690. return nullptr;
  691. }
  692. return &chunks->entries[idx];
  693. }
  694. void mtmd_input_chunks_free(mtmd_input_chunks * chunks) {
  695. if (chunks) {
  696. delete chunks;
  697. }
  698. }
  699. // mtmd_input_chunk
  700. enum mtmd_input_chunk_type mtmd_input_chunk_get_type(const mtmd_input_chunk * chunk) {
  701. return chunk->type;
  702. }
  703. const llama_token * mtmd_input_chunk_get_tokens_text(const mtmd_input_chunk * chunk, size_t * n_tokens_output) {
  704. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  705. *n_tokens_output = chunk->tokens_text.size();
  706. return chunk->tokens_text.data();
  707. }
  708. *n_tokens_output = 0;
  709. return nullptr;
  710. }
  711. const mtmd_image_tokens * mtmd_input_chunk_get_tokens_image(const mtmd_input_chunk * chunk) {
  712. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  713. return chunk->tokens_image.get();
  714. }
  715. return nullptr;
  716. }
  717. size_t mtmd_input_chunk_get_n_tokens(const mtmd_input_chunk * chunk) {
  718. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  719. return chunk->tokens_text.size();
  720. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  721. return mtmd_image_tokens_get_n_tokens(chunk->tokens_image.get());
  722. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
  723. return chunk->tokens_audio->n_tokens;
  724. } else {
  725. GGML_ABORT("invalid chunk type");
  726. }
  727. }
  728. llama_pos mtmd_input_chunk_get_n_pos(const mtmd_input_chunk * chunk) {
  729. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  730. return chunk->tokens_text.size();
  731. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  732. return mtmd_image_tokens_get_n_pos(chunk->tokens_image.get());
  733. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
  734. return chunk->tokens_audio->n_tokens;
  735. } else {
  736. GGML_ABORT("invalid chunk type");
  737. }
  738. }
  739. const char * mtmd_input_chunk_get_id(const mtmd_input_chunk * chunk) {
  740. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  741. return chunk->tokens_image->id.c_str();
  742. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
  743. return chunk->tokens_audio->id.c_str();
  744. }
  745. return nullptr;
  746. }
  747. mtmd_input_chunk * mtmd_input_chunk_copy(const mtmd_input_chunk * chunk) {
  748. mtmd_input_chunk * copy = new mtmd_input_chunk{
  749. chunk->type,
  750. chunk->tokens_text,
  751. nullptr,
  752. nullptr,
  753. };
  754. if (chunk->tokens_image) {
  755. // copy the image tokens
  756. copy->tokens_image = mtmd_image_tokens_ptr(new mtmd_image_tokens());
  757. *copy->tokens_image = chunk->tokens_image->clone();
  758. }
  759. if (chunk->tokens_audio) {
  760. // copy the audio tokens
  761. copy->tokens_audio = mtmd_audio_tokens_ptr(new mtmd_audio_tokens());
  762. *copy->tokens_audio = chunk->tokens_audio->clone();
  763. }
  764. return copy;
  765. }
  766. void mtmd_input_chunk_free(mtmd_input_chunk * chunk) {
  767. if (chunk) {
  768. delete chunk;
  769. }
  770. }
  771. // mtmd_image_tokens
  772. size_t mtmd_image_tokens_get_n_tokens(const mtmd_image_tokens * image_tokens) {
  773. return image_tokens->n_tokens();
  774. }
  775. size_t mtmd_image_tokens_get_nx(const mtmd_image_tokens * image_tokens) {
  776. return image_tokens->nx;
  777. }
  778. size_t mtmd_image_tokens_get_ny(const mtmd_image_tokens * image_tokens) {
  779. return image_tokens->ny;
  780. }
  781. const char * mtmd_image_tokens_get_id(const mtmd_image_tokens * image_tokens) {
  782. return image_tokens->id.c_str();
  783. }
  784. llama_pos mtmd_image_tokens_get_n_pos(const mtmd_image_tokens * image_tokens) {
  785. if (image_tokens->use_mrope_pos) {
  786. return 1; // for M-RoPE, the whole image is 1 in temporal dimension
  787. }
  788. return image_tokens->n_tokens();
  789. }
  790. // test function
  791. mtmd_input_chunks * mtmd_test_create_input_chunks() {
  792. mtmd_input_chunks * chunks = mtmd_input_chunks_init();
  793. if (!chunks) {
  794. return nullptr;
  795. }
  796. // create a text chunk
  797. std::vector<llama_token> tokens_text = { 1, 2, 3, 4, 5 };
  798. mtmd_input_chunk chunk_text{
  799. MTMD_INPUT_CHUNK_TYPE_TEXT,
  800. std::move(tokens_text),
  801. nullptr, // image tokens
  802. nullptr, // audio tokens
  803. };
  804. chunks->entries.emplace_back(std::move(chunk_text));
  805. // create an image chunk
  806. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  807. image_tokens->nx = 4;
  808. image_tokens->ny = 4;
  809. image_tokens->batch_f32.entries.resize(16);
  810. image_tokens->id = "image_1";
  811. mtmd_input_chunk chunk_image{
  812. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  813. {}, // text tokens
  814. std::move(image_tokens),
  815. nullptr, // audio tokens
  816. };
  817. chunks->entries.emplace_back(std::move(chunk_image));
  818. return chunks;
  819. }