mtmd.cpp 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  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_qwen2vl(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. }
  272. }
  273. void init_audio() {
  274. GGML_ASSERT(ctx_a != nullptr);
  275. projector_type proj = clip_get_projector_type(ctx_a);
  276. LOG_WRN("%s: audio input is in experimental stage and may have reduced quality:\n"
  277. " https://github.com/ggml-org/llama.cpp/discussions/13759\n", __func__);
  278. // set preprocessor
  279. switch (proj) {
  280. case PROJECTOR_TYPE_QWEN2A:
  281. case PROJECTOR_TYPE_QWEN25O:
  282. case PROJECTOR_TYPE_ULTRAVOX:
  283. case PROJECTOR_TYPE_VOXTRAL:
  284. audio_preproc = std::make_unique<mtmd_audio_preprocessor_whisper>(ctx_a);
  285. break;
  286. default:
  287. GGML_ABORT("unsupported audio projector type");
  288. }
  289. // initialize audio preprocessor
  290. audio_preproc->initialize();
  291. // set special tokens
  292. if (proj == PROJECTOR_TYPE_QWEN2A) {
  293. // <|audio_bos|> ... (embeddings) ... <|audio_eos|>
  294. aud_beg = "<|audio_bos|>";
  295. aud_end = "<|audio_eos|>";
  296. } else if (proj == PROJECTOR_TYPE_ULTRAVOX) {
  297. // [BEGIN_AUDIO] ... (embeddings) ...
  298. aud_beg = "[BEGIN_AUDIO]";
  299. }
  300. }
  301. // get clip ctx based on chunk type
  302. clip_ctx * get_clip_ctx(const mtmd_input_chunk * chunk) const {
  303. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  304. return ctx_v;
  305. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
  306. return ctx_a;
  307. }
  308. GGML_ABORT("unknown chunk type");
  309. }
  310. projector_type proj_type_v() const {
  311. return ctx_v ? clip_get_projector_type(ctx_v) : PROJECTOR_TYPE_UNKNOWN;
  312. }
  313. projector_type proj_type_a() const {
  314. return ctx_a ? clip_get_projector_type(ctx_a) : PROJECTOR_TYPE_UNKNOWN;
  315. }
  316. ~mtmd_context() {
  317. clip_free(ctx_a);
  318. clip_free(ctx_v);
  319. }
  320. private:
  321. llama_token lookup_token(const std::string & token_text) {
  322. const llama_vocab * vocab = llama_model_get_vocab(text_model);
  323. const int n_vocab = llama_vocab_n_tokens(vocab);
  324. for (int i = 0; i < n_vocab; i++) {
  325. if (token_to_piece(vocab, i, true) == token_text) {
  326. return i;
  327. }
  328. }
  329. return LLAMA_TOKEN_NULL;
  330. }
  331. std::string token_to_piece(const llama_vocab * vocab, llama_token token, bool special) {
  332. std::string piece;
  333. piece.resize(piece.capacity()); // using string internal cache, 15 bytes + '\n'
  334. const int n_chars = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
  335. if (n_chars < 0) {
  336. piece.resize(-n_chars);
  337. int check = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
  338. GGML_ASSERT(check == -n_chars);
  339. } else {
  340. piece.resize(n_chars);
  341. }
  342. return piece;
  343. }
  344. };
  345. mtmd_context * mtmd_init_from_file(const char * mmproj_fname,
  346. const struct llama_model * text_model,
  347. const struct mtmd_context_params ctx_params) {
  348. try {
  349. return new mtmd_context(mmproj_fname, text_model, ctx_params);
  350. } catch (const std::exception & e) {
  351. LOG_ERR("%s: error: %s\n", __func__, e.what());
  352. return nullptr;
  353. }
  354. }
  355. void mtmd_free(mtmd_context * ctx) {
  356. delete ctx;
  357. }
  358. struct mtmd_tokenizer {
  359. mtmd_context * ctx;
  360. std::vector<const mtmd_bitmap *> bitmaps;
  361. std::string input_text;
  362. bool add_special;
  363. bool parse_special;
  364. const llama_vocab * vocab;
  365. mtmd_input_chunks cur;
  366. mtmd_tokenizer(mtmd_context * ctx,
  367. const mtmd_input_text * text,
  368. const mtmd_bitmap ** bitmaps,
  369. size_t n_bitmaps) : ctx(ctx), bitmaps(bitmaps, bitmaps + n_bitmaps) {
  370. add_special = text->add_special;
  371. parse_special = text->parse_special;
  372. input_text = text->text;
  373. vocab = llama_model_get_vocab(ctx->text_model);
  374. // for compatibility, we convert image marker to media marker
  375. string_replace_all(input_text, MTMD_DEFAULT_IMAGE_MARKER, ctx->media_marker);
  376. }
  377. int32_t tokenize(mtmd_input_chunks * output) {
  378. cur.entries.clear();
  379. std::vector<std::string> parts = split_text(input_text, ctx->media_marker);
  380. size_t i_bm = 0; // index of the current bitmap
  381. for (auto & part : parts) {
  382. if (part == ctx->media_marker) {
  383. // this is a marker, we should add the next bitmap
  384. if (i_bm >= bitmaps.size()) {
  385. LOG_ERR("%s: error: number of bitmaps (%zu) does not match number of markers (%zu)\n",
  386. __func__, bitmaps.size(), parts.size() - 1);
  387. return 1;
  388. }
  389. const mtmd_bitmap * bitmap = bitmaps[i_bm++];
  390. int32_t res = add_media(bitmap);
  391. if (res != 0) {
  392. return res;
  393. }
  394. } else {
  395. // this is a text part, we should add it as text
  396. add_text(part, parse_special);
  397. }
  398. }
  399. if (add_special && llama_vocab_get_add_bos(vocab)) {
  400. // if first chunk is text, we add BOS token to first text chunk
  401. // otherwise, create a new text chunk with BOS token
  402. if (!cur.entries.empty() && cur.entries[0].type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  403. // add BOS token to the beginning of first text chunk
  404. cur.entries[0].tokens_text.insert(cur.entries[0].tokens_text.begin(), llama_vocab_bos(vocab));
  405. } else {
  406. // create a new text chunk with BOS token at the beginning
  407. mtmd_input_chunk bos_chunk{
  408. MTMD_INPUT_CHUNK_TYPE_TEXT,
  409. {llama_vocab_bos(vocab)},
  410. nullptr, // image tokens
  411. nullptr, // audio tokens
  412. };
  413. cur.entries.insert(cur.entries.begin(), std::move(bos_chunk));
  414. }
  415. }
  416. if (add_special && llama_vocab_get_add_eos(vocab)) {
  417. // if last chunk is text, we add EOS token to it
  418. add_text({llama_vocab_eos(vocab)});
  419. }
  420. if (i_bm != bitmaps.size()) {
  421. LOG_ERR("%s: error: number of bitmaps (%zu) does not match number of markers (%zu)\n",
  422. __func__, bitmaps.size(), parts.size() - 1);
  423. return 1;
  424. }
  425. *output = std::move(cur);
  426. return 0;
  427. }
  428. void add_text(const std::string & txt, bool parse_special) {
  429. LOG_DBG("%s: %s\n", __func__, txt.c_str());
  430. auto tokens = mtmd_tokenize_text_internal(vocab, txt, /* add_special */ false, parse_special);
  431. add_text(tokens);
  432. }
  433. void add_text(const std::vector<llama_token> & tokens) {
  434. if (tokens.empty()) {
  435. return;
  436. }
  437. // if last entry is also a text chunk, add tokens to it instead of creating new chunk
  438. if (!cur.entries.empty() && cur.entries.back().type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  439. cur.entries.back().tokens_text.insert(
  440. cur.entries.back().tokens_text.end(),
  441. tokens.begin(),
  442. tokens.end());
  443. } else {
  444. mtmd_input_chunk chunk{
  445. MTMD_INPUT_CHUNK_TYPE_TEXT,
  446. tokens,
  447. nullptr, // image tokens
  448. nullptr, // audio tokens
  449. };
  450. cur.entries.emplace_back(std::move(chunk));
  451. }
  452. }
  453. int32_t add_media(const mtmd_bitmap * bitmap) {
  454. if (!bitmap->is_audio) {
  455. // handle image
  456. if (!ctx->ctx_v) {
  457. LOG_ERR("%s: error: model does not support vision input\n", __func__);
  458. return 2;
  459. }
  460. if (!ctx->img_beg.empty()) {
  461. add_text(ctx->img_beg, true); // add image begin token
  462. }
  463. // convert mtmd_bitmap to clip_image_u8
  464. clip_image_u8_ptr img_u8(clip_image_u8_init());
  465. img_u8->nx = bitmap->nx;
  466. img_u8->ny = bitmap->ny;
  467. img_u8->buf.resize(bitmap->data.size());
  468. std::memcpy(img_u8->buf.data(), bitmap->data.data(), img_u8->nx * img_u8->ny * 3);
  469. // preprocess image
  470. clip_image_f32_batch batch_f32;
  471. bool ok = clip_image_preprocess(ctx->ctx_v, img_u8.get(), &batch_f32);
  472. if (!ok) {
  473. LOG_ERR("Unable to preprocess image\n");
  474. return 2;
  475. }
  476. // handle llava-uhd style preprocessing
  477. if (
  478. ctx->slice_tmpl == MTMD_SLICE_TMPL_MINICPMV_2_5
  479. || ctx->slice_tmpl == MTMD_SLICE_TMPL_MINICPMV_2_6
  480. || ctx->slice_tmpl == MTMD_SLICE_TMPL_LLAMA4
  481. || ctx->slice_tmpl == MTMD_SLICE_TMPL_IDEFICS3
  482. ) {
  483. const int n_col = batch_f32.grid_x;
  484. const int n_row = batch_f32.grid_y;
  485. // split batch into chunks of single images
  486. // NOTE: batch_f32 will be invalidated after this call
  487. auto chunks = split_batch_to_chunk(std::move(batch_f32), bitmap->id);
  488. GGML_ASSERT(chunks.size() > 0);
  489. auto ov_chunk = std::move(chunks.front());
  490. chunks.erase(chunks.begin());
  491. // add overview image (first)
  492. if (ctx->ov_img_first) {
  493. add_text(ctx->tok_ov_img_start);
  494. cur.entries.emplace_back(std::move(ov_chunk));
  495. add_text(ctx->tok_ov_img_end);
  496. }
  497. // add slices (or tiles)
  498. if (!chunks.empty()) {
  499. GGML_ASSERT((int)chunks.size() == n_row * n_col);
  500. add_text(ctx->tok_slices_start);
  501. for (int y = 0; y < n_row; y++) {
  502. for (int x = 0; x < n_col; x++) {
  503. const bool is_last_in_row = (x == n_col - 1);
  504. if (!ctx->tok_sli_img_start.empty()) {
  505. add_text(ctx->tok_sli_img_start);
  506. } else if (!ctx->sli_img_start_tmpl.empty()) {
  507. // If using a template to preceed a slice image
  508. const size_t sz = std::snprintf(nullptr, 0, ctx->sli_img_start_tmpl.c_str(), y+1, x+1) + 1;
  509. std::unique_ptr<char[]> buf(new char[sz]);
  510. std::snprintf(buf.get(), sz, ctx->sli_img_start_tmpl.c_str(), y+1, x+1);
  511. add_text(std::string(buf.get(), buf.get() + sz - 1), true);
  512. }
  513. cur.entries.emplace_back(std::move(chunks[y * n_col + x]));
  514. add_text(ctx->tok_sli_img_end);
  515. if (!is_last_in_row) {
  516. add_text(ctx->tok_sli_img_mid);
  517. }
  518. }
  519. if ((y != n_row - 1 || ctx->tok_row_end_trail)) {
  520. add_text(ctx->tok_row_end);
  521. }
  522. }
  523. add_text(ctx->tok_slices_end);
  524. }
  525. // add overview image (last)
  526. if (!ctx->ov_img_first) {
  527. add_text(ctx->tok_ov_img_start);
  528. cur.entries.emplace_back(std::move(ov_chunk));
  529. add_text(ctx->tok_ov_img_end);
  530. }
  531. } else {
  532. size_t n_tokens = 0;
  533. for (const auto & entry : batch_f32.entries) {
  534. n_tokens += clip_n_output_tokens(ctx->ctx_v, entry.get());
  535. }
  536. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  537. if (ctx->use_mrope) {
  538. // for Qwen2VL, we need this information for M-RoPE decoding positions
  539. image_tokens->nx = clip_n_output_tokens_x(ctx->ctx_v, batch_f32.entries[0].get());
  540. image_tokens->ny = clip_n_output_tokens_y(ctx->ctx_v, batch_f32.entries[0].get());
  541. image_tokens->use_mrope_pos = true;
  542. } else {
  543. // other models, we only need the total number of tokens
  544. image_tokens->nx = n_tokens;
  545. image_tokens->ny = 1;
  546. }
  547. image_tokens->batch_f32 = std::move(batch_f32);
  548. image_tokens->id = bitmap->id; // optional
  549. LOG_DBG("image_tokens->nx = %d\n", image_tokens->nx);
  550. LOG_DBG("image_tokens->ny = %d\n", image_tokens->ny);
  551. LOG_DBG("batch_f32 size = %d\n", (int)image_tokens->batch_f32.entries.size());
  552. mtmd_input_chunk chunk{
  553. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  554. {}, // text tokens
  555. std::move(image_tokens),
  556. nullptr, // audio tokens
  557. };
  558. cur.entries.emplace_back(std::move(chunk));
  559. }
  560. if (!ctx->img_end.empty()) {
  561. add_text(ctx->img_end, true); // add image end token
  562. }
  563. } else {
  564. // handle audio
  565. if (!ctx->ctx_a) {
  566. LOG_ERR("%s: error: model does not support audio input\n", __func__);
  567. return 2;
  568. }
  569. if (bitmap->data.size() == 0) {
  570. LOG_ERR("%s: error: empty audio data\n", __func__);
  571. return 2;
  572. }
  573. if (!ctx->aud_beg.empty()) {
  574. add_text(ctx->aud_beg, true); // add audio begin token
  575. }
  576. // preprocess audio
  577. std::vector<mtmd_audio_mel> mel_spec_chunks;
  578. const float * samples = (const float *)bitmap->data.data();
  579. size_t n_samples = bitmap->data.size() / sizeof(float);
  580. bool ok = ctx->audio_preproc->preprocess(samples, n_samples, mel_spec_chunks);
  581. if (!ok) {
  582. LOG_ERR("Unable to preprocess audio\n");
  583. return 2;
  584. }
  585. // consider each mel_spec as a separate audio chunk
  586. // TODO: maybe support batching, but this may come with memory cost
  587. for (auto & mel_spec : mel_spec_chunks) {
  588. clip_image_f32_ptr mel_f32(clip_image_f32_init());
  589. mel_f32->nx = mel_spec.n_len;
  590. mel_f32->ny = mel_spec.n_mel;
  591. mel_f32->buf = std::move(mel_spec.data);
  592. size_t n_tokens = clip_n_output_tokens(ctx->ctx_a, mel_f32.get());
  593. clip_image_f32_batch batch_f32;
  594. batch_f32.is_audio = true;
  595. batch_f32.entries.push_back(std::move(mel_f32));
  596. mtmd_audio_tokens_ptr audio_tokens(new mtmd_audio_tokens);
  597. audio_tokens->n_tokens = n_tokens;
  598. audio_tokens->batch_f32 = std::move(batch_f32);
  599. audio_tokens->id = bitmap->id; // optional
  600. LOG_DBG("audio_tokens->n_tokens = %d\n", audio_tokens->n_tokens);
  601. mtmd_input_chunk chunk{
  602. MTMD_INPUT_CHUNK_TYPE_AUDIO,
  603. {}, // text tokens
  604. nullptr, // image tokens
  605. std::move(audio_tokens),
  606. };
  607. cur.entries.emplace_back(std::move(chunk));
  608. }
  609. if (!ctx->aud_end.empty()) {
  610. add_text(ctx->aud_end, true); // add audio end token
  611. }
  612. }
  613. return 0;
  614. }
  615. std::vector<mtmd_input_chunk> split_batch_to_chunk(clip_image_f32_batch && batch_f32, const std::string & id) {
  616. std::vector<mtmd_input_chunk> chunks;
  617. for (auto & entry : batch_f32.entries) {
  618. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  619. image_tokens->nx = clip_n_output_tokens(ctx->ctx_v, entry.get());
  620. image_tokens->ny = 1;
  621. image_tokens->batch_f32.entries.push_back(std::move(entry));
  622. image_tokens->id = id;
  623. mtmd_input_chunk chunk{
  624. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  625. {}, // text tokens
  626. std::move(image_tokens),
  627. nullptr, // audio tokens
  628. };
  629. chunks.emplace_back(std::move(chunk));
  630. }
  631. return chunks;
  632. }
  633. // for example: "a <__media__> b <__media__> c" --> "a", "<__media__>", "b", "<__media__>", "c"
  634. static std::vector<std::string> split_text(const std::string & input, const std::string & delimiter) {
  635. std::vector<std::string> result;
  636. if (input.empty()) {
  637. return result;
  638. }
  639. size_t start = 0;
  640. size_t pos = 0;
  641. while ((pos = input.find(delimiter, start)) != std::string::npos) {
  642. if (pos > start) {
  643. result.push_back(input.substr(start, pos - start));
  644. }
  645. result.push_back(delimiter);
  646. start = pos + delimiter.length();
  647. }
  648. if (start < input.length()) {
  649. result.push_back(input.substr(start));
  650. }
  651. return result;
  652. }
  653. // copied from common_tokenize
  654. static std::vector<llama_token> mtmd_tokenize_text_internal(
  655. const struct llama_vocab * vocab,
  656. const std::string & text,
  657. bool add_special,
  658. bool parse_special) {
  659. // upper limit for the number of tokens
  660. int n_tokens = text.length() + 2 * add_special;
  661. std::vector<llama_token> result(n_tokens);
  662. n_tokens = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  663. if (n_tokens < 0) {
  664. result.resize(-n_tokens);
  665. int check = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  666. GGML_ASSERT(check == -n_tokens);
  667. } else {
  668. result.resize(n_tokens);
  669. }
  670. return result;
  671. }
  672. };
  673. int32_t mtmd_tokenize(mtmd_context * ctx,
  674. mtmd_input_chunks * output,
  675. const mtmd_input_text * text,
  676. const mtmd_bitmap ** bitmaps,
  677. size_t n_bitmaps) {
  678. mtmd_tokenizer tokenizer(ctx, text, bitmaps, n_bitmaps);
  679. return tokenizer.tokenize(output);
  680. }
  681. int32_t mtmd_encode_chunk(mtmd_context * ctx, const mtmd_input_chunk * chunk) {
  682. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  683. LOG_WRN("mtmd_encode_chunk has no effect for text chunks\n");
  684. return 0;
  685. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  686. if (!ctx->ctx_v) {
  687. LOG_ERR("%s: model does not support vision input\n", __func__);
  688. return 1;
  689. }
  690. return mtmd_encode(ctx, chunk->tokens_image.get());
  691. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
  692. if (!ctx->ctx_a) {
  693. LOG_ERR("%s: model does not support audio input\n", __func__);
  694. return 1;
  695. }
  696. int n_mmproj_embd = ctx->n_embd_text;
  697. ctx->image_embd_v.resize(chunk->tokens_audio->n_tokens * n_mmproj_embd);
  698. bool ok = clip_image_batch_encode(
  699. ctx->ctx_a,
  700. ctx->n_threads,
  701. &chunk->tokens_audio->batch_f32,
  702. ctx->image_embd_v.data());
  703. return ok ? 0 : 1;
  704. }
  705. LOG_ERR("%s: unknown chunk type %d\n", __func__, (int)chunk->type);
  706. return 1;
  707. }
  708. int32_t mtmd_encode(mtmd_context * ctx, const mtmd_image_tokens * image_tokens) {
  709. clip_ctx * ctx_clip = ctx->ctx_v;
  710. if (!ctx_clip) {
  711. LOG_ERR("%s: this API does not support non-vision input, please use mtmd_encode_chunk instead\n", __func__);
  712. return 1;
  713. }
  714. int n_mmproj_embd = clip_n_mmproj_embd(ctx_clip);
  715. ctx->image_embd_v.resize(image_tokens->n_tokens() * n_mmproj_embd);
  716. bool ok = false;
  717. if (clip_is_llava(ctx_clip)
  718. || clip_is_minicpmv(ctx_clip)
  719. || clip_is_glm(ctx_clip)) {
  720. // TODO @ngxson : llava does not support batched encoding ; this should be fixed inside clip_image_batch_encode()
  721. const auto & entries = image_tokens->batch_f32.entries;
  722. for (size_t i = 0; i < entries.size(); i++) {
  723. int n_tokens_per_image = clip_n_output_tokens(ctx_clip, entries[i].get());
  724. ok = clip_image_encode(
  725. ctx_clip,
  726. ctx->n_threads,
  727. entries[i].get(),
  728. ctx->image_embd_v.data() + i*n_mmproj_embd*n_tokens_per_image);
  729. }
  730. } else {
  731. ok = clip_image_batch_encode(
  732. ctx_clip,
  733. ctx->n_threads,
  734. &image_tokens->batch_f32,
  735. ctx->image_embd_v.data());
  736. }
  737. return ok ? 0 : 1;
  738. }
  739. float * mtmd_get_output_embd(mtmd_context * ctx) {
  740. return ctx->image_embd_v.data();
  741. }
  742. bool mtmd_decode_use_non_causal(mtmd_context * ctx) {
  743. if (ctx->ctx_v && clip_get_projector_type(ctx->ctx_v) == PROJECTOR_TYPE_GEMMA3) {
  744. return true;
  745. }
  746. return false;
  747. }
  748. bool mtmd_decode_use_mrope(mtmd_context * ctx) {
  749. return ctx->use_mrope;
  750. }
  751. bool mtmd_support_vision(mtmd_context * ctx) {
  752. return ctx->ctx_v != nullptr;
  753. }
  754. bool mtmd_support_audio(mtmd_context * ctx) {
  755. return ctx->ctx_a != nullptr;
  756. }
  757. int mtmd_get_audio_bitrate(mtmd_context * ctx) {
  758. if (!ctx->ctx_a) {
  759. return -1;
  760. }
  761. return clip_get_hparams(ctx->ctx_a)->audio_sample_rate;
  762. }
  763. //
  764. // public API functions
  765. //
  766. // mtmd_bitmap
  767. mtmd_bitmap * mtmd_bitmap_init(uint32_t nx,
  768. uint32_t ny,
  769. const unsigned char * data) {
  770. mtmd_bitmap * bitmap = new mtmd_bitmap;
  771. bitmap->nx = nx;
  772. bitmap->ny = ny;
  773. size_t data_size = (size_t)nx * ny * 3;
  774. bitmap->data.resize(data_size);
  775. std::memcpy(bitmap->data.data(), data, data_size);
  776. return bitmap;
  777. }
  778. mtmd_bitmap * mtmd_bitmap_init_from_audio(size_t n_samples,
  779. const float * data) {
  780. mtmd_bitmap * bitmap = new mtmd_bitmap;
  781. bitmap->nx = n_samples;
  782. bitmap->ny = 1;
  783. bitmap->is_audio = true;
  784. size_t data_size = n_samples * sizeof(float);
  785. bitmap->data.resize(data_size);
  786. std::memcpy(bitmap->data.data(), data, data_size);
  787. return bitmap;
  788. }
  789. uint32_t mtmd_bitmap_get_nx(const mtmd_bitmap * bitmap) {
  790. return bitmap->nx;
  791. }
  792. uint32_t mtmd_bitmap_get_ny(const mtmd_bitmap * bitmap) {
  793. return bitmap->ny;
  794. }
  795. const unsigned char * mtmd_bitmap_get_data(const mtmd_bitmap * bitmap) {
  796. return bitmap->data.data();
  797. }
  798. size_t mtmd_bitmap_get_n_bytes(const mtmd_bitmap * bitmap) {
  799. return bitmap->data.size();
  800. }
  801. bool mtmd_bitmap_is_audio(const mtmd_bitmap * bitmap) {
  802. return bitmap->is_audio;
  803. }
  804. const char * mtmd_bitmap_get_id(const mtmd_bitmap * bitmap) {
  805. return bitmap->id.c_str();
  806. }
  807. void mtmd_bitmap_set_id(mtmd_bitmap * bitmap, const char * id) {
  808. if (id) {
  809. bitmap->id = std::string(id);
  810. } else {
  811. bitmap->id.clear();
  812. }
  813. }
  814. void mtmd_bitmap_free(mtmd_bitmap * bitmap) {
  815. if (bitmap) {
  816. delete bitmap;
  817. }
  818. }
  819. // mtmd_input_chunks
  820. mtmd_input_chunks * mtmd_input_chunks_init() {
  821. return new mtmd_input_chunks;
  822. }
  823. size_t mtmd_input_chunks_size(const mtmd_input_chunks * chunks) {
  824. return chunks->entries.size();
  825. }
  826. const mtmd_input_chunk * mtmd_input_chunks_get(const mtmd_input_chunks * chunks, size_t idx) {
  827. if (idx >= chunks->entries.size()) {
  828. return nullptr;
  829. }
  830. return &chunks->entries[idx];
  831. }
  832. void mtmd_input_chunks_free(mtmd_input_chunks * chunks) {
  833. if (chunks) {
  834. delete chunks;
  835. }
  836. }
  837. // mtmd_input_chunk
  838. enum mtmd_input_chunk_type mtmd_input_chunk_get_type(const mtmd_input_chunk * chunk) {
  839. return chunk->type;
  840. }
  841. const llama_token * mtmd_input_chunk_get_tokens_text(const mtmd_input_chunk * chunk, size_t * n_tokens_output) {
  842. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  843. *n_tokens_output = chunk->tokens_text.size();
  844. return chunk->tokens_text.data();
  845. }
  846. *n_tokens_output = 0;
  847. return nullptr;
  848. }
  849. const mtmd_image_tokens * mtmd_input_chunk_get_tokens_image(const mtmd_input_chunk * chunk) {
  850. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  851. return chunk->tokens_image.get();
  852. }
  853. return nullptr;
  854. }
  855. size_t mtmd_input_chunk_get_n_tokens(const mtmd_input_chunk * chunk) {
  856. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  857. return chunk->tokens_text.size();
  858. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  859. return mtmd_image_tokens_get_n_tokens(chunk->tokens_image.get());
  860. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
  861. return chunk->tokens_audio->n_tokens;
  862. } else {
  863. GGML_ABORT("invalid chunk type");
  864. }
  865. }
  866. llama_pos mtmd_input_chunk_get_n_pos(const mtmd_input_chunk * chunk) {
  867. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  868. return chunk->tokens_text.size();
  869. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  870. return mtmd_image_tokens_get_n_pos(chunk->tokens_image.get());
  871. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
  872. return chunk->tokens_audio->n_tokens;
  873. } else {
  874. GGML_ABORT("invalid chunk type");
  875. }
  876. }
  877. const char * mtmd_input_chunk_get_id(const mtmd_input_chunk * chunk) {
  878. if (chunk->type == MTMD_INPUT_CHUNK_TYPE_IMAGE) {
  879. return chunk->tokens_image->id.c_str();
  880. } else if (chunk->type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
  881. return chunk->tokens_audio->id.c_str();
  882. }
  883. return nullptr;
  884. }
  885. mtmd_input_chunk * mtmd_input_chunk_copy(const mtmd_input_chunk * chunk) {
  886. mtmd_input_chunk * copy = new mtmd_input_chunk{
  887. chunk->type,
  888. chunk->tokens_text,
  889. nullptr,
  890. nullptr,
  891. };
  892. if (chunk->tokens_image) {
  893. // copy the image tokens
  894. copy->tokens_image = mtmd_image_tokens_ptr(new mtmd_image_tokens());
  895. *copy->tokens_image = chunk->tokens_image->clone();
  896. }
  897. if (chunk->tokens_audio) {
  898. // copy the audio tokens
  899. copy->tokens_audio = mtmd_audio_tokens_ptr(new mtmd_audio_tokens());
  900. *copy->tokens_audio = chunk->tokens_audio->clone();
  901. }
  902. return copy;
  903. }
  904. void mtmd_input_chunk_free(mtmd_input_chunk * chunk) {
  905. if (chunk) {
  906. delete chunk;
  907. }
  908. }
  909. // mtmd_image_tokens
  910. size_t mtmd_image_tokens_get_n_tokens(const mtmd_image_tokens * image_tokens) {
  911. return image_tokens->n_tokens();
  912. }
  913. size_t mtmd_image_tokens_get_nx(const mtmd_image_tokens * image_tokens) {
  914. return image_tokens->nx;
  915. }
  916. size_t mtmd_image_tokens_get_ny(const mtmd_image_tokens * image_tokens) {
  917. return image_tokens->ny;
  918. }
  919. const char * mtmd_image_tokens_get_id(const mtmd_image_tokens * image_tokens) {
  920. return image_tokens->id.c_str();
  921. }
  922. llama_pos mtmd_image_tokens_get_n_pos(const mtmd_image_tokens * image_tokens) {
  923. if (image_tokens->use_mrope_pos) {
  924. // for M-RoPE, temporal dimension = max(t,h,w)
  925. // t is omitted as we don't support video input
  926. return std::max(image_tokens->nx, image_tokens->ny);
  927. }
  928. return image_tokens->n_tokens();
  929. }
  930. // test function
  931. mtmd_input_chunks * mtmd_test_create_input_chunks() {
  932. mtmd_input_chunks * chunks = mtmd_input_chunks_init();
  933. if (!chunks) {
  934. return nullptr;
  935. }
  936. // create a text chunk
  937. std::vector<llama_token> tokens_text = { 1, 2, 3, 4, 5 };
  938. mtmd_input_chunk chunk_text{
  939. MTMD_INPUT_CHUNK_TYPE_TEXT,
  940. std::move(tokens_text),
  941. nullptr, // image tokens
  942. nullptr, // audio tokens
  943. };
  944. chunks->entries.emplace_back(std::move(chunk_text));
  945. // create an image chunk
  946. mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens);
  947. image_tokens->nx = 4;
  948. image_tokens->ny = 4;
  949. image_tokens->batch_f32.entries.resize(16);
  950. image_tokens->id = "image_1";
  951. mtmd_input_chunk chunk_image{
  952. MTMD_INPUT_CHUNK_TYPE_IMAGE,
  953. {}, // text tokens
  954. std::move(image_tokens),
  955. nullptr, // audio tokens
  956. };
  957. chunks->entries.emplace_back(std::move(chunk_image));
  958. return chunks;
  959. }
  960. void mtmd_log_set(ggml_log_callback log_callback, void * user_data) {
  961. g_logger_state.log_callback = log_callback ? log_callback : clip_log_callback_default;
  962. g_logger_state.log_callback_user_data = user_data;
  963. }