mtmd.cpp 41 KB

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