1
0

mtmd.cpp 40 KB

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