mtmd.cpp 34 KB

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