mtmd.cpp 41 KB

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