mtmd.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  1. #include "clip.h"
  2. #include "clip-impl.h"
  3. #include "mtmd.h"
  4. #include "mtmd-audio.h"
  5. #include "llama.h"
  6. // fix problem with std::min and std::max
  7. #if defined(_WIN32)
  8. #define WIN32_LEAN_AND_MEAN
  9. #ifndef NOMINMAX
  10. # define NOMINMAX
  11. #endif
  12. #include <windows.h>
  13. #endif
  14. #include <algorithm>
  15. #include <cerrno>
  16. #include <cstdio>
  17. #include <cstdlib>
  18. #include <cstring>
  19. #include <vector>
  20. // represents raw image data, layout is RGBRGBRGB...
  21. // length of data must be nx * ny * 3
  22. struct mtmd_bitmap {
  23. uint32_t nx;
  24. uint32_t ny;
  25. std::vector<unsigned char> data;
  26. std::string id; // optional user-defined id, for ex: can be set to image hash, useful for KV cache tracking
  27. bool is_audio = false; // true if the bitmap is audio
  28. };
  29. struct mtmd_image_tokens {
  30. uint32_t nx; // number of tokens in x direction
  31. uint32_t ny; // number of tokens in y direction
  32. bool use_mrope_pos = false; // use M-RoPE position counting (the whole image is 1 temporal position)
  33. uint32_t n_tokens() const { return nx * ny; }
  34. clip_image_f32_batch batch_f32; // preprocessed image patches
  35. std::string id; // optional user-defined ID, useful for KV cache tracking
  36. mtmd_image_tokens clone() {
  37. return mtmd_image_tokens{
  38. nx,
  39. ny,
  40. use_mrope_pos,
  41. batch_f32.clone(),
  42. id
  43. };
  44. }
  45. };
  46. using mtmd_image_tokens_ptr = std::unique_ptr<mtmd_image_tokens>;
  47. struct mtmd_audio_tokens {
  48. uint32_t n_tokens; // number of tokens
  49. clip_image_f32_batch batch_f32; // preprocessed image patches
  50. std::string id; // optional user-defined ID, useful for KV cache tracking
  51. mtmd_audio_tokens clone() {
  52. return mtmd_audio_tokens{
  53. n_tokens,
  54. batch_f32.clone(),
  55. id
  56. };
  57. }
  58. };
  59. using mtmd_audio_tokens_ptr = std::unique_ptr<mtmd_audio_tokens>;
  60. struct mtmd_input_chunk {
  61. mtmd_input_chunk_type type;
  62. std::vector<llama_token> tokens_text;
  63. mtmd_image_tokens_ptr tokens_image;
  64. mtmd_audio_tokens_ptr tokens_audio;
  65. };
  66. struct mtmd_input_chunks {
  67. std::vector<mtmd_input_chunk> entries;
  68. };
  69. // slice template, used by some llava-uhd models to correctly place the special tokens around image embeddings
  70. // models not having it (llava-1.6) will process embeddings without any special tokens in-between
  71. enum mtmd_slice_tmpl {
  72. MTMD_SLICE_TMPL_NONE,
  73. MTMD_SLICE_TMPL_MINICPMV_2_5,
  74. MTMD_SLICE_TMPL_MINICPMV_2_6,
  75. MTMD_SLICE_TMPL_LLAMA4,
  76. MTMD_SLICE_TMPL_IDEFICS3,
  77. };
  78. const char * mtmd_default_marker() {
  79. return "<__media__>";
  80. }
  81. static clip_flash_attn_type mtmd_get_clip_flash_attn_type(enum llama_flash_attn_type flash_attn_type) {
  82. switch (flash_attn_type) {
  83. case LLAMA_FLASH_ATTN_TYPE_AUTO: return CLIP_FLASH_ATTN_TYPE_AUTO;
  84. case LLAMA_FLASH_ATTN_TYPE_DISABLED: return CLIP_FLASH_ATTN_TYPE_DISABLED;
  85. case LLAMA_FLASH_ATTN_TYPE_ENABLED: return CLIP_FLASH_ATTN_TYPE_ENABLED;
  86. }
  87. return CLIP_FLASH_ATTN_TYPE_AUTO;
  88. }
  89. mtmd_context_params mtmd_context_params_default() {
  90. mtmd_context_params params {
  91. /* use_gpu */ true,
  92. /* print_timings */ true,
  93. /* n_threads */ 4,
  94. /* image_marker */ MTMD_DEFAULT_IMAGE_MARKER,
  95. /* media_marker */ mtmd_default_marker(),
  96. /* flash_attn_type */ LLAMA_FLASH_ATTN_TYPE_AUTO,
  97. /* warmup */ true,
  98. /* image_min_tokens */ -1,
  99. /* image_max_tokens */ -1,
  100. };
  101. return params;
  102. }
  103. struct mtmd_context {
  104. struct clip_ctx * ctx_v; // vision
  105. struct clip_ctx * ctx_a; // audio
  106. const struct llama_model * text_model;
  107. std::vector<float> image_embd_v; // image embedding vector
  108. bool print_timings;
  109. int n_threads;
  110. std::string media_marker;
  111. const int n_embd_text;
  112. // these are not token, but strings used to mark the beginning and end of image/audio embeddings
  113. std::string img_beg;
  114. std::string img_end;
  115. std::string aud_beg;
  116. std::string aud_end;
  117. // for llava-uhd style models, we need special tokens in-between slices
  118. // minicpmv calls them "slices", llama 4 calls them "tiles"
  119. mtmd_slice_tmpl slice_tmpl = MTMD_SLICE_TMPL_NONE;
  120. std::vector<llama_token> tok_ov_img_start; // overview image
  121. std::vector<llama_token> tok_ov_img_end; // overview image
  122. std::vector<llama_token> tok_slices_start; // start of all slices
  123. std::vector<llama_token> tok_slices_end; // end of all slices
  124. std::vector<llama_token> tok_sli_img_start; // single slice start
  125. std::vector<llama_token> tok_sli_img_end; // single slice end
  126. std::vector<llama_token> tok_sli_img_mid; // between 2 slices
  127. std::vector<llama_token> tok_row_end; // end of row
  128. bool tok_row_end_trail = false;
  129. bool ov_img_first = false;
  130. bool use_mrope = false; // for Qwen2VL, we need to use M-RoPE
  131. // string template for slice image delimiters with row/col (idefics3)
  132. std::string sli_img_start_tmpl;
  133. std::unique_ptr<mtmd_audio_preprocessor> audio_preproc;
  134. // TODO @ngxson : add timings
  135. mtmd_context(const char * mmproj_fname,
  136. const llama_model * text_model,
  137. const mtmd_context_params & ctx_params) :
  138. text_model (text_model),
  139. print_timings(ctx_params.print_timings),
  140. n_threads (ctx_params.n_threads),
  141. media_marker (ctx_params.media_marker),
  142. n_embd_text (llama_model_n_embd_inp(text_model))
  143. {
  144. if (std::string(ctx_params.image_marker) != MTMD_DEFAULT_IMAGE_MARKER) {
  145. throw std::runtime_error("custom image_marker is not supported anymore, use media_marker instead");
  146. }
  147. if (media_marker.empty()) {
  148. throw std::runtime_error("media_marker must not be empty");
  149. }
  150. clip_context_params ctx_clip_params {
  151. /* use_gpu */ ctx_params.use_gpu,
  152. /* flash_attn_type */ CLIP_FLASH_ATTN_TYPE_AUTO,
  153. /* image_min_tokens */ ctx_params.image_min_tokens,
  154. /* image_max_tokens */ ctx_params.image_max_tokens,
  155. /* warmup */ ctx_params.warmup,
  156. };
  157. auto res = clip_init(mmproj_fname, ctx_clip_params);
  158. ctx_v = res.ctx_v;
  159. ctx_a = res.ctx_a;
  160. if (!ctx_v && !ctx_a) {
  161. throw std::runtime_error(string_format("Failed to load CLIP model from %s\n", mmproj_fname));
  162. }
  163. // if both vision and audio mmproj are present, we need to validate their n_embd
  164. if (ctx_v && ctx_a) {
  165. int n_embd_v = clip_n_mmproj_embd(ctx_v);
  166. int n_embd_a = clip_n_mmproj_embd(ctx_a);
  167. if (n_embd_v != n_embd_a) {
  168. throw std::runtime_error(string_format(
  169. "mismatch between vision and audio mmproj (n_embd_v = %d, n_embd_a = %d)\n",
  170. n_embd_v, n_embd_a));
  171. }
  172. }
  173. // since we already validate n_embd of vision and audio mmproj,
  174. // we can safely assume that they are the same
  175. int n_embd_clip = clip_n_mmproj_embd(ctx_v ? ctx_v : ctx_a);
  176. if (n_embd_text != n_embd_clip) {
  177. throw std::runtime_error(string_format(
  178. "mismatch between text model (n_embd = %d) and mmproj (n_embd = %d)\n"
  179. "hint: you may be using wrong mmproj\n",
  180. n_embd_text, n_embd_clip));
  181. }
  182. if (ctx_v) {
  183. init_vision();
  184. }
  185. if (ctx_a) {
  186. init_audio();
  187. }
  188. }
  189. void init_vision() {
  190. GGML_ASSERT(ctx_v != nullptr);
  191. use_mrope = clip_is_mrope(ctx_v);
  192. projector_type proj = clip_get_projector_type(ctx_v);
  193. int minicpmv_version = clip_is_minicpmv(ctx_v);
  194. if (minicpmv_version == 2) {
  195. // minicpmv 2.5 format:
  196. // <image> (overview) </image><slice><image> (slice) </image><image> (slice) </image>\n ... </slice>
  197. slice_tmpl = MTMD_SLICE_TMPL_MINICPMV_2_5;
  198. tok_ov_img_start = {lookup_token("<image>")};
  199. tok_ov_img_end = {lookup_token("</image>")};
  200. tok_slices_start = {lookup_token("<slice>")};
  201. tok_slices_end = {lookup_token("</slice>")};
  202. tok_sli_img_start = tok_ov_img_start;
  203. tok_sli_img_end = tok_ov_img_end;
  204. tok_row_end = {lookup_token("\n")};
  205. tok_row_end_trail = false; // no trailing end-of-row token
  206. ov_img_first = true;
  207. } else if (minicpmv_version == 3 || minicpmv_version == 4 || minicpmv_version == 5 || minicpmv_version == 6) {
  208. // minicpmv 2.6 format:
  209. // <image> (overview) </image><slice> (slice) </slice><slice> (slice) </slice>\n ...
  210. slice_tmpl = MTMD_SLICE_TMPL_MINICPMV_2_6;
  211. tok_ov_img_start = {lookup_token("<image>")};
  212. tok_ov_img_end = {lookup_token("</image>")};
  213. tok_sli_img_start = {lookup_token("<slice>")};
  214. tok_sli_img_end = {lookup_token("</slice>")};
  215. tok_row_end = {lookup_token("\n")};
  216. tok_row_end_trail = false; // no trailing end-of-row token
  217. ov_img_first = true;
  218. } else if (minicpmv_version != 0) {
  219. GGML_ASSERT(false && "unsupported minicpmv version");
  220. } else if (proj == PROJECTOR_TYPE_LLAMA4) {
  221. // llama 4 format:
  222. // <|image_start|>
  223. // (slice) <|tile_x_separator|> (slice) <|tile_x_separator|> ... <|tile_y_separator|>
  224. // (slice) <|tile_x_separator|> (slice) <|tile_x_separator|> ... <|tile_y_separator|>
  225. // ... <|tile_y_separator|> <-- trailing end-of-row token
  226. // <|image|> (overview) <-- overview image is last
  227. // <|image_end|>
  228. slice_tmpl = MTMD_SLICE_TMPL_LLAMA4;
  229. tok_ov_img_start = {lookup_token("<|image|>")};
  230. tok_sli_img_mid = {lookup_token("<|tile_x_separator|>")};
  231. tok_row_end = {lookup_token("<|tile_y_separator|>")};
  232. tok_row_end_trail = true; // add trailing end-of-row token
  233. ov_img_first = false; // overview image is last
  234. }
  235. // set boi/eoi
  236. if (proj == PROJECTOR_TYPE_GEMMA3) {
  237. // <start_of_image> ... (image embeddings) ... <end_of_image>
  238. img_beg = "<start_of_image>";
  239. img_end = "<end_of_image>";
  240. } else if (proj == PROJECTOR_TYPE_IDEFICS3) {
  241. // https://github.com/huggingface/transformers/blob/a42ba80fa520c784c8f11a973ca9034e5f859b79/src/transformers/models/idefics3/processing_idefics3.py#L192-L215
  242. slice_tmpl = MTMD_SLICE_TMPL_IDEFICS3;
  243. tok_ov_img_start = {lookup_token("\n\n"), lookup_token("<fake_token_around_image>"), lookup_token("<global-img>")};
  244. tok_ov_img_end = {lookup_token("<fake_token_around_image>")};
  245. tok_row_end = {lookup_token("\n")};
  246. sli_img_start_tmpl = "<fake_token_around_image><row_%d_col_%d>";
  247. } else if (proj == PROJECTOR_TYPE_PIXTRAL) {
  248. // https://github.com/huggingface/transformers/blob/1cd110c6cb6a6237614130c470e9a902dbc1a4bd/docs/source/en/model_doc/pixtral.md
  249. img_end = "[IMG_END]";
  250. } else if (proj == PROJECTOR_TYPE_QWEN2VL || proj == PROJECTOR_TYPE_QWEN25VL || proj == PROJECTOR_TYPE_QWEN3VL) {
  251. // <|vision_start|> ... (image embeddings) ... <|vision_end|>
  252. img_beg = "<|vision_start|>";
  253. img_end = "<|vision_end|>";
  254. } else if (proj == PROJECTOR_TYPE_LLAMA4) {
  255. // (more details in mtmd_context constructor)
  256. img_beg = "<|image_start|>";
  257. img_end = "<|image_end|>";
  258. LOG_WRN("%s: llama 4 vision is known to have degraded quality:\n"
  259. " https://github.com/ggml-org/llama.cpp/pull/13282\n", __func__);
  260. } else if (proj == PROJECTOR_TYPE_INTERNVL) {
  261. // <img> ... (image embeddings) ... </img>
  262. img_beg = "<img>";
  263. img_end = "</img>";
  264. } else if (proj == PROJECTOR_TYPE_LIGHTONOCR) {
  265. // <|im_start|> ... (image embeddings) ... <|im_end|>
  266. img_beg = "<|im_start|>";
  267. img_end = "<|im_end|>";
  268. } else if (proj == PROJECTOR_TYPE_LFM2) {
  269. img_beg = "<|image_start|>";
  270. img_end = "<|image_end|>";
  271. } else if (proj == PROJECTOR_TYPE_GLM4V) {
  272. img_beg = "<|begin_of_image|>";
  273. img_end = "<|end_of_image|>";
  274. }
  275. }
  276. void init_audio() {
  277. GGML_ASSERT(ctx_a != nullptr);
  278. projector_type proj = clip_get_projector_type(ctx_a);
  279. LOG_WRN("%s: audio input is in experimental stage and may have reduced quality:\n"
  280. " https://github.com/ggml-org/llama.cpp/discussions/13759\n", __func__);
  281. // set preprocessor
  282. switch (proj) {
  283. case PROJECTOR_TYPE_QWEN2A:
  284. case PROJECTOR_TYPE_QWEN25O:
  285. case PROJECTOR_TYPE_ULTRAVOX:
  286. case PROJECTOR_TYPE_VOXTRAL:
  287. audio_preproc = std::make_unique<mtmd_audio_preprocessor_whisper>(ctx_a);
  288. break;
  289. default:
  290. GGML_ABORT("unsupported audio projector type");
  291. }
  292. // initialize audio preprocessor
  293. audio_preproc->initialize();
  294. // set special tokens
  295. if (proj == PROJECTOR_TYPE_QWEN2A) {
  296. // <|audio_bos|> ... (embeddings) ... <|audio_eos|>
  297. aud_beg = "<|audio_bos|>";
  298. aud_end = "<|audio_eos|>";
  299. } else if (proj == PROJECTOR_TYPE_ULTRAVOX) {
  300. // [BEGIN_AUDIO] ... (embeddings) ...
  301. aud_beg = "[BEGIN_AUDIO]";
  302. }
  303. }
  304. // get clip ctx based on chunk type
  305. clip_ctx * get_clip_ctx(const mtmd_input_chunk * chunk) const {
  306. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  307. return ctx_v;
  308. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
  309. return ctx_a;
  310. }
  311. GGML_ABORT("unknown chunk type");
  312. }
  313. projector_type proj_type_v() const {
  314. return ctx_v ? clip_get_projector_type(ctx_v) : PROJECTOR_TYPE_UNKNOWN;
  315. }
  316. projector_type proj_type_a() const {
  317. return ctx_a ? clip_get_projector_type(ctx_a) : PROJECTOR_TYPE_UNKNOWN;
  318. }
  319. ~mtmd_context() {
  320. clip_free(ctx_a);
  321. clip_free(ctx_v);
  322. }
  323. private:
  324. llama_token lookup_token(const std::string & token_text) {
  325. const llama_vocab * vocab = llama_model_get_vocab(text_model);
  326. const int n_vocab = llama_vocab_n_tokens(vocab);
  327. for (int i = 0; i < n_vocab; i++) {
  328. if (token_to_piece(vocab, i, true) == token_text) {
  329. return i;
  330. }
  331. }
  332. return LLAMA_TOKEN_NULL;
  333. }
  334. std::string token_to_piece(const llama_vocab * vocab, llama_token token, bool special) {
  335. std::string piece;
  336. piece.resize(piece.capacity()); // using string internal cache, 15 bytes + '\n'
  337. const int n_chars = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
  338. if (n_chars < 0) {
  339. piece.resize(-n_chars);
  340. int check = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
  341. GGML_ASSERT(check == -n_chars);
  342. } else {
  343. piece.resize(n_chars);
  344. }
  345. return piece;
  346. }
  347. };
  348. mtmd_context * mtmd_init_from_file(const char * mmproj_fname,
  349. const struct llama_model * text_model,
  350. const struct mtmd_context_params ctx_params) {
  351. try {
  352. return new mtmd_context(mmproj_fname, text_model, ctx_params);
  353. } catch (const std::exception & e) {
  354. LOG_ERR("%s: error: %s\n", __func__, e.what());
  355. return nullptr;
  356. }
  357. }
  358. void mtmd_free(mtmd_context * ctx) {
  359. delete ctx;
  360. }
  361. struct mtmd_tokenizer {
  362. mtmd_context * ctx;
  363. std::vector<const mtmd_bitmap *> bitmaps;
  364. std::string input_text;
  365. bool add_special;
  366. bool parse_special;
  367. const llama_vocab * vocab;
  368. mtmd_input_chunks cur;
  369. mtmd_tokenizer(mtmd_context * ctx,
  370. const mtmd_input_text * text,
  371. const mtmd_bitmap ** bitmaps,
  372. size_t n_bitmaps) : ctx(ctx), bitmaps(bitmaps, bitmaps + n_bitmaps) {
  373. add_special = text->add_special;
  374. parse_special = text->parse_special;
  375. input_text = text->text;
  376. vocab = llama_model_get_vocab(ctx->text_model);
  377. // for compatibility, we convert image marker to media marker
  378. string_replace_all(input_text, MTMD_DEFAULT_IMAGE_MARKER, ctx->media_marker);
  379. }
  380. int32_t tokenize(mtmd_input_chunks * output) {
  381. cur.entries.clear();
  382. std::vector<std::string> parts = split_text(input_text, ctx->media_marker);
  383. size_t i_bm = 0; // index of the current bitmap
  384. for (auto & part : parts) {
  385. if (part == ctx->media_marker) {
  386. // this is a marker, we should add the next bitmap
  387. if (i_bm >= bitmaps.size()) {
  388. LOG_ERR("%s: error: number of bitmaps (%zu) does not match number of markers (%zu)\n",
  389. __func__, bitmaps.size(), parts.size() - 1);
  390. return 1;
  391. }
  392. const mtmd_bitmap * bitmap = bitmaps[i_bm++];
  393. int32_t res = add_media(bitmap);
  394. if (res != 0) {
  395. return res;
  396. }
  397. } else {
  398. // this is a text part, we should add it as text
  399. add_text(part, parse_special);
  400. }
  401. }
  402. if (add_special && llama_vocab_get_add_bos(vocab)) {
  403. // if first chunk is text, we add BOS token to first text chunk
  404. // otherwise, create a new text chunk with BOS token
  405. if (!cur.entries.empty() && cur.entries[0].type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  406. // add BOS token to the beginning of first text chunk
  407. cur.entries[0].tokens_text.insert(cur.entries[0].tokens_text.begin(), llama_vocab_bos(vocab));
  408. } else {
  409. // create a new text chunk with BOS token at the beginning
  410. mtmd_input_chunk bos_chunk{
  411. MTMD_INPUT_CHUNK_TYPE_TEXT,
  412. {llama_vocab_bos(vocab)},
  413. nullptr, // image tokens
  414. nullptr, // audio tokens
  415. };
  416. cur.entries.insert(cur.entries.begin(), std::move(bos_chunk));
  417. }
  418. }
  419. if (add_special && llama_vocab_get_add_eos(vocab)) {
  420. // if last chunk is text, we add EOS token to it
  421. add_text({llama_vocab_eos(vocab)});
  422. }
  423. if (i_bm != bitmaps.size()) {
  424. LOG_ERR("%s: error: number of bitmaps (%zu) does not match number of markers (%zu)\n",
  425. __func__, bitmaps.size(), parts.size() - 1);
  426. return 1;
  427. }
  428. *output = std::move(cur);
  429. return 0;
  430. }
  431. void add_text(const std::string & txt, bool parse_special) {
  432. LOG_DBG("%s: %s\n", __func__, txt.c_str());
  433. auto tokens = mtmd_tokenize_text_internal(vocab, txt, /* add_special */ false, parse_special);
  434. add_text(tokens);
  435. }
  436. void add_text(const std::vector<llama_token> & tokens) {
  437. if (tokens.empty()) {
  438. return;
  439. }
  440. // if last entry is also a text chunk, add tokens to it instead of creating new chunk
  441. if (!cur.entries.empty() && cur.entries.back().type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  442. cur.entries.back().tokens_text.insert(
  443. cur.entries.back().tokens_text.end(),
  444. tokens.begin(),
  445. tokens.end());
  446. } else {
  447. mtmd_input_chunk chunk{
  448. MTMD_INPUT_CHUNK_TYPE_TEXT,
  449. tokens,
  450. nullptr, // image tokens
  451. nullptr, // audio tokens
  452. };
  453. cur.entries.emplace_back(std::move(chunk));
  454. }
  455. }
  456. int32_t add_media(const mtmd_bitmap * bitmap) {
  457. if (!bitmap->is_audio) {
  458. // handle image
  459. if (!ctx->ctx_v) {
  460. LOG_ERR("%s: error: model does not support vision input\n", __func__);
  461. return 2;
  462. }
  463. if (!ctx->img_beg.empty()) {
  464. add_text(ctx->img_beg, true); // add image begin token
  465. }
  466. // convert mtmd_bitmap to clip_image_u8
  467. clip_image_u8_ptr img_u8(clip_image_u8_init());
  468. img_u8->nx = bitmap->nx;
  469. img_u8->ny = bitmap->ny;
  470. img_u8->buf.resize(bitmap->data.size());
  471. std::memcpy(img_u8->buf.data(), bitmap->data.data(), img_u8->nx * img_u8->ny * 3);
  472. // preprocess image
  473. clip_image_f32_batch batch_f32;
  474. bool ok = clip_image_preprocess(ctx->ctx_v, img_u8.get(), &batch_f32);
  475. if (!ok) {
  476. LOG_ERR("Unable to preprocess image\n");
  477. return 2;
  478. }
  479. // handle llava-uhd style preprocessing
  480. if (
  481. ctx->slice_tmpl == MTMD_SLICE_TMPL_MINICPMV_2_5
  482. || ctx->slice_tmpl == MTMD_SLICE_TMPL_MINICPMV_2_6
  483. || ctx->slice_tmpl == MTMD_SLICE_TMPL_LLAMA4
  484. || ctx->slice_tmpl == MTMD_SLICE_TMPL_IDEFICS3
  485. ) {
  486. const int n_col = batch_f32.grid_x;
  487. const int n_row = batch_f32.grid_y;
  488. // split batch into chunks of single images
  489. // NOTE: batch_f32 will be invalidated after this call
  490. auto chunks = split_batch_to_chunk(std::move(batch_f32), bitmap->id);
  491. GGML_ASSERT(chunks.size() > 0);
  492. auto ov_chunk = std::move(chunks.front());
  493. chunks.erase(chunks.begin());
  494. // add overview image (first)
  495. if (ctx->ov_img_first) {
  496. add_text(ctx->tok_ov_img_start);
  497. cur.entries.emplace_back(std::move(ov_chunk));
  498. add_text(ctx->tok_ov_img_end);
  499. }
  500. // add slices (or tiles)
  501. if (!chunks.empty()) {
  502. GGML_ASSERT((int)chunks.size() == n_row * n_col);
  503. add_text(ctx->tok_slices_start);
  504. for (int y = 0; y < n_row; y++) {
  505. for (int x = 0; x < n_col; x++) {
  506. const bool is_last_in_row = (x == n_col - 1);
  507. if (!ctx->tok_sli_img_start.empty()) {
  508. add_text(ctx->tok_sli_img_start);
  509. } else if (!ctx->sli_img_start_tmpl.empty()) {
  510. // If using a template to preceed a slice image
  511. const size_t sz = std::snprintf(nullptr, 0, ctx->sli_img_start_tmpl.c_str(), y+1, x+1) + 1;
  512. std::unique_ptr<char[]> buf(new char[sz]);
  513. std::snprintf(buf.get(), sz, ctx->sli_img_start_tmpl.c_str(), y+1, x+1);
  514. add_text(std::string(buf.get(), buf.get() + sz - 1), true);
  515. }
  516. cur.entries.emplace_back(std::move(chunks[y * n_col + x]));
  517. add_text(ctx->tok_sli_img_end);
  518. if (!is_last_in_row) {
  519. add_text(ctx->tok_sli_img_mid);
  520. }
  521. }
  522. if ((y != n_row - 1 || ctx->tok_row_end_trail)) {
  523. add_text(ctx->tok_row_end);
  524. }
  525. }
  526. add_text(ctx->tok_slices_end);
  527. }
  528. // add overview image (last)
  529. if (!ctx->ov_img_first) {
  530. add_text(ctx->tok_ov_img_start);
  531. cur.entries.emplace_back(std::move(ov_chunk));
  532. add_text(ctx->tok_ov_img_end);
  533. }
  534. } else {
  535. size_t n_tokens = 0;
  536. for (const auto & entry : batch_f32.entries) {
  537. n_tokens += clip_n_output_tokens(ctx->ctx_v, entry.get());
  538. }
  539. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  540. if (ctx->use_mrope) {
  541. // for Qwen2VL, we need this information for M-RoPE decoding positions
  542. image_tokens->nx = clip_n_output_tokens_x(ctx->ctx_v, batch_f32.entries[0].get());
  543. image_tokens->ny = clip_n_output_tokens_y(ctx->ctx_v, batch_f32.entries[0].get());
  544. image_tokens->use_mrope_pos = true;
  545. } else {
  546. // other models, we only need the total number of tokens
  547. image_tokens->nx = n_tokens;
  548. image_tokens->ny = 1;
  549. }
  550. image_tokens->batch_f32 = std::move(batch_f32);
  551. image_tokens->id = bitmap->id; // optional
  552. LOG_DBG("image_tokens->nx = %d\n", image_tokens->nx);
  553. LOG_DBG("image_tokens->ny = %d\n", image_tokens->ny);
  554. LOG_DBG("batch_f32 size = %d\n", (int)image_tokens->batch_f32.entries.size());
  555. mtmd_input_chunk chunk{
  556. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  557. {}, // text tokens
  558. std::move(image_tokens),
  559. nullptr, // audio tokens
  560. };
  561. cur.entries.emplace_back(std::move(chunk));
  562. }
  563. if (!ctx->img_end.empty()) {
  564. add_text(ctx->img_end, true); // add image end token
  565. }
  566. } else {
  567. // handle audio
  568. if (!ctx->ctx_a) {
  569. LOG_ERR("%s: error: model does not support audio input\n", __func__);
  570. return 2;
  571. }
  572. if (bitmap->data.size() == 0) {
  573. LOG_ERR("%s: error: empty audio data\n", __func__);
  574. return 2;
  575. }
  576. if (!ctx->aud_beg.empty()) {
  577. add_text(ctx->aud_beg, true); // add audio begin token
  578. }
  579. // preprocess audio
  580. std::vector<mtmd_audio_mel> mel_spec_chunks;
  581. const float * samples = (const float *)bitmap->data.data();
  582. size_t n_samples = bitmap->data.size() / sizeof(float);
  583. bool ok = ctx->audio_preproc->preprocess(samples, n_samples, mel_spec_chunks);
  584. if (!ok) {
  585. LOG_ERR("Unable to preprocess audio\n");
  586. return 2;
  587. }
  588. // consider each mel_spec as a separate audio chunk
  589. // TODO: maybe support batching, but this may come with memory cost
  590. for (auto & mel_spec : mel_spec_chunks) {
  591. clip_image_f32_ptr mel_f32(clip_image_f32_init());
  592. mel_f32->nx = mel_spec.n_len;
  593. mel_f32->ny = mel_spec.n_mel;
  594. mel_f32->buf = std::move(mel_spec.data);
  595. size_t n_tokens = clip_n_output_tokens(ctx->ctx_a, mel_f32.get());
  596. clip_image_f32_batch batch_f32;
  597. batch_f32.is_audio = true;
  598. batch_f32.entries.push_back(std::move(mel_f32));
  599. mtmd_audio_tokens_ptr audio_tokens(new mtmd_audio_tokens);
  600. audio_tokens->n_tokens = n_tokens;
  601. audio_tokens->batch_f32 = std::move(batch_f32);
  602. audio_tokens->id = bitmap->id; // optional
  603. LOG_DBG("audio_tokens->n_tokens = %d\n", audio_tokens->n_tokens);
  604. mtmd_input_chunk chunk{
  605. MTMD_INPUT_CHUNK_TYPE_AUDIO,
  606. {}, // text tokens
  607. nullptr, // image tokens
  608. std::move(audio_tokens),
  609. };
  610. cur.entries.emplace_back(std::move(chunk));
  611. }
  612. if (!ctx->aud_end.empty()) {
  613. add_text(ctx->aud_end, true); // add audio end token
  614. }
  615. }
  616. return 0;
  617. }
  618. std::vector<mtmd_input_chunk> split_batch_to_chunk(clip_image_f32_batch && batch_f32, const std::string & id) {
  619. std::vector<mtmd_input_chunk> chunks;
  620. for (auto & entry : batch_f32.entries) {
  621. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  622. image_tokens->nx = clip_n_output_tokens(ctx->ctx_v, entry.get());
  623. image_tokens->ny = 1;
  624. image_tokens->batch_f32.entries.push_back(std::move(entry));
  625. image_tokens->id = id;
  626. mtmd_input_chunk chunk{
  627. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  628. {}, // text tokens
  629. std::move(image_tokens),
  630. nullptr, // audio tokens
  631. };
  632. chunks.emplace_back(std::move(chunk));
  633. }
  634. return chunks;
  635. }
  636. // for example: "a <__media__> b <__media__> c" --> "a", "<__media__>", "b", "<__media__>", "c"
  637. static std::vector<std::string> split_text(const std::string & input, const std::string & delimiter) {
  638. std::vector<std::string> result;
  639. if (input.empty()) {
  640. return result;
  641. }
  642. size_t start = 0;
  643. size_t pos = 0;
  644. while ((pos = input.find(delimiter, start)) != std::string::npos) {
  645. if (pos > start) {
  646. result.push_back(input.substr(start, pos - start));
  647. }
  648. result.push_back(delimiter);
  649. start = pos + delimiter.length();
  650. }
  651. if (start < input.length()) {
  652. result.push_back(input.substr(start));
  653. }
  654. return result;
  655. }
  656. // copied from common_tokenize
  657. static std::vector<llama_token> mtmd_tokenize_text_internal(
  658. const struct llama_vocab * vocab,
  659. const std::string & text,
  660. bool add_special,
  661. bool parse_special) {
  662. // upper limit for the number of tokens
  663. int n_tokens = text.length() + 2 * add_special;
  664. std::vector<llama_token> result(n_tokens);
  665. n_tokens = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  666. if (n_tokens < 0) {
  667. result.resize(-n_tokens);
  668. int check = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  669. GGML_ASSERT(check == -n_tokens);
  670. } else {
  671. result.resize(n_tokens);
  672. }
  673. return result;
  674. }
  675. };
  676. int32_t mtmd_tokenize(mtmd_context * ctx,
  677. mtmd_input_chunks * output,
  678. const mtmd_input_text * text,
  679. const mtmd_bitmap ** bitmaps,
  680. size_t n_bitmaps) {
  681. mtmd_tokenizer tokenizer(ctx, text, bitmaps, n_bitmaps);
  682. return tokenizer.tokenize(output);
  683. }
  684. int32_t mtmd_encode_chunk(mtmd_context * ctx, const mtmd_input_chunk * chunk) {
  685. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  686. LOG_WRN("mtmd_encode_chunk has no effect for text chunks\n");
  687. return 0;
  688. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  689. if (!ctx->ctx_v) {
  690. LOG_ERR("%s: model does not support vision input\n", __func__);
  691. return 1;
  692. }
  693. return mtmd_encode(ctx, chunk->tokens_image.get());
  694. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
  695. if (!ctx->ctx_a) {
  696. LOG_ERR("%s: model does not support audio input\n", __func__);
  697. return 1;
  698. }
  699. int n_mmproj_embd = ctx->n_embd_text;
  700. ctx->image_embd_v.resize(chunk->tokens_audio->n_tokens * n_mmproj_embd);
  701. bool ok = clip_image_batch_encode(
  702. ctx->ctx_a,
  703. ctx->n_threads,
  704. &chunk->tokens_audio->batch_f32,
  705. ctx->image_embd_v.data());
  706. return ok ? 0 : 1;
  707. }
  708. LOG_ERR("%s: unknown chunk type %d\n", __func__, (int)chunk->type);
  709. return 1;
  710. }
  711. int32_t mtmd_encode(mtmd_context * ctx, const mtmd_image_tokens * image_tokens) {
  712. clip_ctx * ctx_clip = ctx->ctx_v;
  713. if (!ctx_clip) {
  714. LOG_ERR("%s: this API does not support non-vision input, please use mtmd_encode_chunk instead\n", __func__);
  715. return 1;
  716. }
  717. int n_mmproj_embd = clip_n_mmproj_embd(ctx_clip);
  718. ctx->image_embd_v.resize(image_tokens->n_tokens() * n_mmproj_embd);
  719. bool ok = false;
  720. if (clip_is_llava(ctx_clip)
  721. || clip_is_minicpmv(ctx_clip)
  722. || clip_is_glm(ctx_clip)) {
  723. // TODO @ngxson : llava does not support batched encoding ; this should be fixed inside clip_image_batch_encode()
  724. const auto & entries = image_tokens->batch_f32.entries;
  725. for (size_t i = 0; i < entries.size(); i++) {
  726. int n_tokens_per_image = clip_n_output_tokens(ctx_clip, entries[i].get());
  727. ok = clip_image_encode(
  728. ctx_clip,
  729. ctx->n_threads,
  730. entries[i].get(),
  731. ctx->image_embd_v.data() + i*n_mmproj_embd*n_tokens_per_image);
  732. }
  733. } else {
  734. ok = clip_image_batch_encode(
  735. ctx_clip,
  736. ctx->n_threads,
  737. &image_tokens->batch_f32,
  738. ctx->image_embd_v.data());
  739. }
  740. return ok ? 0 : 1;
  741. }
  742. float * mtmd_get_output_embd(mtmd_context * ctx) {
  743. return ctx->image_embd_v.data();
  744. }
  745. bool mtmd_decode_use_non_causal(mtmd_context * ctx) {
  746. if (ctx->ctx_v && clip_get_projector_type(ctx->ctx_v) == PROJECTOR_TYPE_GEMMA3) {
  747. return true;
  748. }
  749. return false;
  750. }
  751. bool mtmd_decode_use_mrope(mtmd_context * ctx) {
  752. return ctx->use_mrope;
  753. }
  754. bool mtmd_support_vision(mtmd_context * ctx) {
  755. return ctx->ctx_v != nullptr;
  756. }
  757. bool mtmd_support_audio(mtmd_context * ctx) {
  758. return ctx->ctx_a != nullptr;
  759. }
  760. int mtmd_get_audio_bitrate(mtmd_context * ctx) {
  761. if (!ctx->ctx_a) {
  762. return -1;
  763. }
  764. return clip_get_hparams(ctx->ctx_a)->audio_sample_rate;
  765. }
  766. //
  767. // public API functions
  768. //
  769. // mtmd_bitmap
  770. mtmd_bitmap * mtmd_bitmap_init(uint32_t nx,
  771. uint32_t ny,
  772. const unsigned char * data) {
  773. mtmd_bitmap * bitmap = new mtmd_bitmap;
  774. bitmap->nx = nx;
  775. bitmap->ny = ny;
  776. size_t data_size = (size_t)nx * ny * 3;
  777. bitmap->data.resize(data_size);
  778. std::memcpy(bitmap->data.data(), data, data_size);
  779. return bitmap;
  780. }
  781. mtmd_bitmap * mtmd_bitmap_init_from_audio(size_t n_samples,
  782. const float * data) {
  783. mtmd_bitmap * bitmap = new mtmd_bitmap;
  784. bitmap->nx = n_samples;
  785. bitmap->ny = 1;
  786. bitmap->is_audio = true;
  787. size_t data_size = n_samples * sizeof(float);
  788. bitmap->data.resize(data_size);
  789. std::memcpy(bitmap->data.data(), data, data_size);
  790. return bitmap;
  791. }
  792. uint32_t mtmd_bitmap_get_nx(const mtmd_bitmap * bitmap) {
  793. return bitmap->nx;
  794. }
  795. uint32_t mtmd_bitmap_get_ny(const mtmd_bitmap * bitmap) {
  796. return bitmap->ny;
  797. }
  798. const unsigned char * mtmd_bitmap_get_data(const mtmd_bitmap * bitmap) {
  799. return bitmap->data.data();
  800. }
  801. size_t mtmd_bitmap_get_n_bytes(const mtmd_bitmap * bitmap) {
  802. return bitmap->data.size();
  803. }
  804. bool mtmd_bitmap_is_audio(const mtmd_bitmap * bitmap) {
  805. return bitmap->is_audio;
  806. }
  807. const char * mtmd_bitmap_get_id(const mtmd_bitmap * bitmap) {
  808. return bitmap->id.c_str();
  809. }
  810. void mtmd_bitmap_set_id(mtmd_bitmap * bitmap, const char * id) {
  811. if (id) {
  812. bitmap->id = std::string(id);
  813. } else {
  814. bitmap->id.clear();
  815. }
  816. }
  817. void mtmd_bitmap_free(mtmd_bitmap * bitmap) {
  818. if (bitmap) {
  819. delete bitmap;
  820. }
  821. }
  822. // mtmd_input_chunks
  823. mtmd_input_chunks * mtmd_input_chunks_init() {
  824. return new mtmd_input_chunks;
  825. }
  826. size_t mtmd_input_chunks_size(const mtmd_input_chunks * chunks) {
  827. return chunks->entries.size();
  828. }
  829. const mtmd_input_chunk * mtmd_input_chunks_get(const mtmd_input_chunks * chunks, size_t idx) {
  830. if (idx >= chunks->entries.size()) {
  831. return nullptr;
  832. }
  833. return &chunks->entries[idx];
  834. }
  835. void mtmd_input_chunks_free(mtmd_input_chunks * chunks) {
  836. if (chunks) {
  837. delete chunks;
  838. }
  839. }
  840. // mtmd_input_chunk
  841. enum mtmd_input_chunk_type mtmd_input_chunk_get_type(const mtmd_input_chunk * chunk) {
  842. return chunk->type;
  843. }
  844. const llama_token * mtmd_input_chunk_get_tokens_text(const mtmd_input_chunk * chunk, size_t * n_tokens_output) {
  845. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  846. *n_tokens_output = chunk->tokens_text.size();
  847. return chunk->tokens_text.data();
  848. }
  849. *n_tokens_output = 0;
  850. return nullptr;
  851. }
  852. const mtmd_image_tokens * mtmd_input_chunk_get_tokens_image(const mtmd_input_chunk * chunk) {
  853. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  854. return chunk->tokens_image.get();
  855. }
  856. return nullptr;
  857. }
  858. size_t mtmd_input_chunk_get_n_tokens(const mtmd_input_chunk * chunk) {
  859. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  860. return chunk->tokens_text.size();
  861. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  862. return mtmd_image_tokens_get_n_tokens(chunk->tokens_image.get());
  863. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
  864. return chunk->tokens_audio->n_tokens;
  865. } else {
  866. GGML_ABORT("invalid chunk type");
  867. }
  868. }
  869. llama_pos mtmd_input_chunk_get_n_pos(const mtmd_input_chunk * chunk) {
  870. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  871. return chunk->tokens_text.size();
  872. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  873. return mtmd_image_tokens_get_n_pos(chunk->tokens_image.get());
  874. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
  875. return chunk->tokens_audio->n_tokens;
  876. } else {
  877. GGML_ABORT("invalid chunk type");
  878. }
  879. }
  880. const char * mtmd_input_chunk_get_id(const mtmd_input_chunk * chunk) {
  881. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  882. return chunk->tokens_image->id.c_str();
  883. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
  884. return chunk->tokens_audio->id.c_str();
  885. }
  886. return nullptr;
  887. }
  888. mtmd_input_chunk * mtmd_input_chunk_copy(const mtmd_input_chunk * chunk) {
  889. mtmd_input_chunk * copy = new mtmd_input_chunk{
  890. chunk->type,
  891. chunk->tokens_text,
  892. nullptr,
  893. nullptr,
  894. };
  895. if (chunk->tokens_image) {
  896. // copy the image tokens
  897. copy->tokens_image = mtmd_image_tokens_ptr(new mtmd_image_tokens());
  898. *copy->tokens_image = chunk->tokens_image->clone();
  899. }
  900. if (chunk->tokens_audio) {
  901. // copy the audio tokens
  902. copy->tokens_audio = mtmd_audio_tokens_ptr(new mtmd_audio_tokens());
  903. *copy->tokens_audio = chunk->tokens_audio->clone();
  904. }
  905. return copy;
  906. }
  907. void mtmd_input_chunk_free(mtmd_input_chunk * chunk) {
  908. if (chunk) {
  909. delete chunk;
  910. }
  911. }
  912. // mtmd_image_tokens
  913. size_t mtmd_image_tokens_get_n_tokens(const mtmd_image_tokens * image_tokens) {
  914. return image_tokens->n_tokens();
  915. }
  916. size_t mtmd_image_tokens_get_nx(const mtmd_image_tokens * image_tokens) {
  917. return image_tokens->nx;
  918. }
  919. size_t mtmd_image_tokens_get_ny(const mtmd_image_tokens * image_tokens) {
  920. return image_tokens->ny;
  921. }
  922. const char * mtmd_image_tokens_get_id(const mtmd_image_tokens * image_tokens) {
  923. return image_tokens->id.c_str();
  924. }
  925. llama_pos mtmd_image_tokens_get_n_pos(const mtmd_image_tokens * image_tokens) {
  926. if (image_tokens->use_mrope_pos) {
  927. // for M-RoPE, temporal dimension = max(t,h,w)
  928. // t is omitted as we don't support video input
  929. return std::max(image_tokens->nx, image_tokens->ny);
  930. }
  931. return image_tokens->n_tokens();
  932. }
  933. // test function
  934. mtmd_input_chunks * mtmd_test_create_input_chunks() {
  935. mtmd_input_chunks * chunks = mtmd_input_chunks_init();
  936. if (!chunks) {
  937. return nullptr;
  938. }
  939. // create a text chunk
  940. std::vector<llama_token> tokens_text = { 1, 2, 3, 4, 5 };
  941. mtmd_input_chunk chunk_text{
  942. MTMD_INPUT_CHUNK_TYPE_TEXT,
  943. std::move(tokens_text),
  944. nullptr, // image tokens
  945. nullptr, // audio tokens
  946. };
  947. chunks->entries.emplace_back(std::move(chunk_text));
  948. // create an image chunk
  949. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  950. image_tokens->nx = 4;
  951. image_tokens->ny = 4;
  952. image_tokens->batch_f32.entries.resize(16);
  953. image_tokens->id = "image_1";
  954. mtmd_input_chunk chunk_image{
  955. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  956. {}, // text tokens
  957. std::move(image_tokens),
  958. nullptr, // audio tokens
  959. };
  960. chunks->entries.emplace_back(std::move(chunk_image));
  961. return chunks;
  962. }
  963. void mtmd_log_set(ggml_log_callback log_callback, void * user_data) {
  964. g_logger_state.log_callback = log_callback ? log_callback : clip_log_callback_default;
  965. g_logger_state.log_callback_user_data = user_data;
  966. }