mtmd.cpp 39 KB

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