mtmd.cpp 41 KB

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